MongoDB $ where查询对nodejs始终为真 [英] Mongodb $where query always true with nodejs

查看:223
本文介绍了MongoDB $ where查询对nodejs始终为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I query my database with a function passed in the "$where" clause in nodejs, it always return me all documents in the db.

例如,如果我这样做

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

它将所有文件退还给我. 相反,如果我这样做

it return me all the documents. Instead, if I do

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

该函数实际上已执行,并且此代码不返回任何文档.

the function is really executed, and this code doesn't return any document.

问题是,如果我将字符串转换为函数,则上下文的bindinds将被删除,而对于更复杂的查询,则需要它们.例如:

The problem is that if I convert in string my function the context's bindinds are removed, and I need them for more complex query. For example:

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

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

Is this a normal behaviour? How can I solve my problem? Please excuse me for my poor english!

推荐答案

首先,请记住,出于解释

First off, keep in mind that the $where operator should almost never be used for the reasons explained here (credit goes to @WiredPrairie).

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

Back to your issue, the approach you'd like to take won't work even in the mongodb shell (which explicitly allows naked js functions with the $where operator). The javascript code provided to the $where operator is executed on the mongo server and won't have access to the enclosing environment (the "context bindings").

> 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({})的等价物,它将返回集合中的所有文档.

Moreover it looks like that the node.js native mongo driver behaves differently from the shell in that it doesn't automatically serialize a js function you provide in the query object and instead it likely drops the clause altogether. This will leave you with the equivalent of timetables.find({}) which will return all the documents in the collection.

这篇关于MongoDB $ where查询对nodejs始终为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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