Search code examples
javascriptnode.jsmongoosemongodb-queryjavascript-objects

Mysteriously Invalid Mongoose Query


I'm getting stuck on a stubborn bug in my MEPN app.

This pseudo-code is supposed to assemble a Mongoose query from the options submitted in a user form, and then search a collection using that query.

var query = [];
query.push("{name:"+req.body.name+"}");
query.push("{status:{$in:["+req.body.statusarray+"]}}");
query.push("{range:{$gte:"+req.body.min+",$lte:"+req.body.max+"}}");

Collection.find(query, function(error, cursor){
  if(error) console.log("ERROR: "+error);
  else //do something
})

Instead, it's printing ERROR: ObjectParameterError: Parameter "filter" to find() must be an object, got {name: 'foobar'},{status : {$in : ['1','2','3']}},{range: {$gte:'0',$lte:'100'}}

Using Collection.find(JSON.parse(query), ...)} instead results in SyntaxError: Unexpected token n in JSON at position 1

Then if I encase the query in { } brackets before passing it to JSON.parse(), it prints Unexpected token { in JSON at position 1

Is there something wrong with the way I am constructing this query?


Solution

  • Collection.find() wants an Object, but you are passing it an array of strings, which is why you're getting that error.

    You can make an object a lot of ways, but the simplest is to just make an object literal:

    var query = {
        name: req.body.name,
        status: {$in:req.body.statusarray},
        range: {$gte: req.body.min, $lte:req.body.max }
    }