当我使用在nodejs中的"$ where"子句中传递的函数查询我的数据库时,它总是返回db中的所有文档.
例如,如果我这样做
var stream = timetables.find({$where: function() { return false; }}).stream();
Run Code Online (Sandbox Code Playgroud)
它将所有文件归还给我.相反,如果我这样做
var stream = timetables.find({$where: 'function() { return false; }'}).stream();
Run Code Online (Sandbox Code Playgroud)
该函数实际执行,此代码不返回任何文档.
问题是,如果我在字符串my function中转换上下文的绑定被删除,我需要它们来进行更复杂的查询.例如:
var n = 1;
var f = function() { return this.number == n; }
var stream = timetables.find({$where: f.toString()}).stream();
// error: n is not defined
Run Code Online (Sandbox Code Playgroud)
这是正常行为吗?我怎样才能解决我的问题?请原谅我英语不好!
首先,请记住,$where出于此处所述的原因,切勿使用该运算符(贷记为@WiredPrairie)。
回到您的问题,即使在mongodb shell(显式允许$where操作员使用裸js函数)中,您要采用的方法也不起作用。提供给$where操作员的javascript代码是在mongo服务器上执行的,无法访问封闭环境(“上下文绑定”)。
> db.test.insert({a: 42})
> db.test.find({a: 42})
{ "_id" : ObjectId("5150433c73f604984a7dff91"), "a" : 42 }
> db.test.find({$where: function() { return this.a == 42 }}) // works
{ "_id" : ObjectId("5150433c73f604984a7dff91"), "a" : 42 }
> var local_var = 42
> db.test.find({$where: function() { return this.a == local_var }})
error: {
"$err" : "error on invocation of $where function:\nJS Error: ReferenceError: local_var is not defined nofile_b:1",
"code" : 10071
}
Run Code Online (Sandbox Code Playgroud)
此外,似乎node.js本机mongo驱动程序的行为与shell有所不同,因为它不会自动序列化您在查询对象中提供的js函数,而是可能会完全删除该子句。这将为您提供与之等效的功能timetables.find({}),它将返回集合中的所有文档。
| 归档时间: |
|
| 查看次数: |
8190 次 |
| 最近记录: |