gpt4 book ai didi

node.js - mongodb $where 查询对于 nodejs 始终为真

转载 作者:IT老高 更新时间:2023-10-28 13:25:55 28 4
gpt4 key购买 nike

当我使用 nodejs 中“$where”子句中传递的函数查询我的数据库时,它总是返回我数据库中的所有文档。

例如,如果我这样做

var stream = timetables.find({$where: function() { return false; }}).stream();

它把所有的文件都还给我。相反,如果我这样做了

var stream = timetables.find({$where: 'function() { return false; }'}).stream();

函数真正执行了,这段代码没有返回任何文档。

问题是,如果我在字符串中转换我的函数,上下文的绑定(bind)将被删除,我需要它们来进行更复杂的查询。例如:

var n = 1;
var f = function() { return this.number == n; }
var stream = timetables.find({$where: f.toString()}).stream();
// error: n is not defined

这是正常行为吗?我该如何解决我的问题?请原谅我的英语不好!

最佳答案

首先,记住 $where 操作符几乎不应该被使用,原因解释 here (归功于@WiredPrairie)。

回到您的问题,即使在 mongodb shell(它明确允许使用 $where 运算符的裸 js 函数)中,您想要采用的方法也不起作用。提供给 $where 运算符的 javascript 代码在 mongo 服务器上执行,并且无法访问封闭环境(“上下文绑定(bind)”)。

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

此外,node.js 原生 mongo 驱动程序的行为似乎与 shell 不同,因为它不会自动序列化您在查询对象中提供的 js 函数,而是可能完全删除该子句。这将为您留下等效的 timetables.find({}) ,它将返回集合中的所有文档。

关于node.js - mongodb $where 查询对于 nodejs 始终为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15612947/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com