Dadsquatch
Dadsquatch

Reputation: 566

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.

Upvotes: 0

Views: 102

Answers (1)

Arun Ghosh
Arun Ghosh

Reputation: 7734

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

Upvotes: 2

Related Questions