Reputation: 43
Heyo, I'd like to know if there's a way I can search for a dynamic variable in a mongodb findOne. Ex something that would work like:
var find = 'userID'
var id = '<some id>'
db.collection.findOne({
eval(find): eval(id)
}, (err, data) => {
if(err) {
console.log(err); return;
}
if(data) {
//Do stuff
}
});
Upvotes: 0
Views: 69
Reputation: 59523
findOne
expects a normal JSON, try this notation:
findOne({[find]: id})
Following notations are all equivalent:
field = "a";
val = 1;
printjsononeline({ a: 1 });
printjsononeline({ a: val });
printjsononeline({ [field]: 1});
printjsononeline({ [field]: val });
Upvotes: 2