Mysteriously Invalid Mongoose Query

╄→尐↘猪︶ㄣ 提交于 2021-01-29 07:35:46

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/51642955/mysteriously-invalid-mongoose-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!