user2355012
user2355012

Reputation: 13

Mongoose query: how to pass a variable

How do I pass 'n' instead of hard coded '5' in Xcom.find({ $where : "this.NIC_No == '5'" } below?

exports.query_by_nic = function ( req, res ){
  var n = req.body.NIC_No;
  console.log(n); //n prints correctly as expected
  Xcom.find({ $where : "this.NIC_No == '5'" }, function ( err, xcoms ){ //works with '5' but how do I query for 'n'?
     res.render( 'query_by_nic', {
        title   : 'Query by NIC',
        xcoms   : xcoms
    });
    console.log(err);
    console.log(xcoms);
  });
};

Upvotes: 1

Views: 2151

Answers (2)

TheHippo
TheHippo

Reputation: 63139

You could do:

Xcom.find({ $where : "this.NIC_No == '" + variableThatContainsNumber + "'" }, function ( err, xcoms ){
    ...
});

Or even better:

Xcom.find({NIC_No: variableThatContainsNumber}, function(err, doc) {
    ...
});

The second one is much better because it does not require JavaScript execution within MongoDB.

Upvotes: 4

matthewtole
matthewtole

Reputation: 3247

This will work:

{ $where : "this.NIC_No == '" + n + "'" }

Although you're passing in a value that the user could directly set, which probably isn't a great idea. If n is always a number, be safer to make sure using something like:

 var n = parseInt(req.body.NIC_No, 10);

And if n is always a number, you don't need to put it in quotes in the query either:

{ $where : "this.NIC_No == " + n }

Upvotes: 0

Related Questions