Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use a variable for the field name in a find() in mongoose?

Say you have a very long generic function you want to use over multiple schemas, and each schema has a different name for the field you're querying (and possibly different type of value -- string, number, etc.)

function foo (field, value){
    Model.find({field: value});
}

foo('idfoo', 'xx');
foo('idbar', 5);

I tried to do something like this as a proof of concept in mongoose and it seems it will only work if you use a variable for value, but you can't for field.

Is this impossible?

like image 646
PGT Avatar asked Dec 01 '13 09:12

PGT


1 Answers

Just put the variable in []

function foo (field, value){
    Model.find({[field]: value});
}

foo('idfoo', 'xx');
foo('idbar', 5);
like image 79
KiwenLau Avatar answered Sep 18 '22 15:09

KiwenLau