CodingNoob CodingNoob - 4 months ago 39
Node.js Question

Javascript - Dynamic function for Mongoose queries

I am looking to do some registration form validation that when submitted it checks the database for existing data matches.

// Check if username is available or not
var existsInDatabase = function(field, value){
console.log('Working with: ', field + ' ' + value); // Console logs the appropriate fields & values
User.find({ field : value }, function(err, docs){
if(docs){
console.log(docs); // console.log shows []
}
});
};


If change my User.find() query to have the variables I am passing into the function it pulls finds the resource in Mongo.

Thanks in advance for any help/guidance.

Answer

You can try:

  var query = {};
  query[field] = value;
  User.find(query, function(err, docs){
    if(docs){
      console.log(docs); // console.log shows []
    }
  });

And if you are using ES6, you can:

  User.find({ [field] : value }, function(err, docs){
    if(docs){
      console.log(docs); // console.log shows []
    }
  });