How do I pass variables in mongojs query in the key name
Question
Each document in my users collection looks like this:
access: { 123456789012345678901234: 3, 123456789012345678901235: 2, 123456789012345678901234: 1, 123456789012345678901236: 0 }
I'm trying to find all records which have access.123456789012345678901234
greater than 0 and this is how I wrote the function. (The value 123456789012345678901234 is passed to the function in the parameter companyid)
findUsersInCompany: function(companyid, callback) {
base.db.users.find({ "access." + companyid: { "$gt": 0 } }, function(err, usersList) {
if( err ) callback(err);
else if( _.isEmpty(usersList) ) callback(1016);
else callback( null, usersList );
});
}
However, I get an error which says 'Unexpected token +'
Any help on how to get this to work would be really helpful.
Solution
You have to build up your find
selector ahead of the call like this:
var selector = {};
selector["access." + companyid] = { "$gt": 0 };
base.db.users.find(selector, function(err, usersList) {
...
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow