神秘无效的猫鼬查询 [英] Mysteriously Invalid Mongoose Query

查看:65
本文介绍了神秘无效的猫鼬查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被MEPN应用程序中的一个顽固错误困住了.

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

该伪代码应该从用户表单中提交的选项中组合一个Mongoose查询,然后使用该查询搜索集合.

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

相反,它正在打印ERROR: ObjectParameterError: Parameter "filter" to find() must be an object, got {name: 'foobar'},{status : {$in : ['1','2','3']}},{range: {$gte:'0',$lte:'100'}}

使用Collection.find(JSON.parse(query), ...)}相反会导致SyntaxError: Unexpected token n in JSON at position 1

然后,如果在将查询传递给JSON.parse()之前将查询括在{}中,它将显示Unexpected token { 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?

推荐答案

Collection.find()想要一个对象,但是您要向其传递一个字符串数组,这就是为什么会出现此错误的原因.

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

这篇关于神秘无效的猫鼬查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆