Search code examples
javascriptnode.jsmongodbvariablesfind

Search for dynamic variable using eval in mongodb


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
  }
});


Solution

  • 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 });