如何在MongoDB中使用外部变量'where'通过Javascript查询? [英] How to use an external variable in MongoDB 'where' query via Javascript?

查看:72
本文介绍了如何在MongoDB中使用外部变量'where'通过Javascript查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MongoDB查询,它在所有属性中搜索搜索变量中定义的值。它的工作方式如下:

I have a MongoDB query that searches all properties for a value defined in the search variable. It works the following way:

 db.collection.findOne({
                $where: function() {
                    var search = 'searchstring';
                    for (var key in this) {
                        if (this[key] === search) {
                          return true;
                        }
                        return false;
                    }
                }
            });

但是,我想在查询之外定义搜索变量。

However, I would like to define the search variable outside the query.

但是当我这样做时,我得到一个错误,它没有被引用(即范围问题):

But when I do so, I get an error that it is not referenced (i.e. scoping issue):

"ReferenceError: search is not defined near '[key] === search

如何使用或将变量传递给查询过滤器?

How can I use or pass the variable to the query filter?

推荐答案

搜索是您在客户端中定义的变量,可能是shell或任何客户端API。

search is a variable that you define in your client, may be the shell, or any client API.

您为 $ where 子句,不会在客户端执行,而是在 mongodb 服务器上执行。
所以,当在服务器端解释函数并且它查找搜索变量时,它从未在服务器上定义,因此您会收到错误。

The function that you define for the $where clause, will not be executed on the client side, but on the mongodb server. so, when the function is being interpreted in the server side and it looks for the search variable, it was never defined on the server and hence you get the error.

在您的情况下,您希望变量 search ,在服务器上执行之前由客户端替换为其内容除非你建立这个功能,否则这是不可能的内容本身在客户端。

In your case, you want the variable search, to be replaced with its content, by the client, before being executed on the server. And this is not possible, unless you build the function content itself in the client side.

客户端从未真正解释您在匿名函数中编写的任何内容。 服务器。您看到的错误来自服务器。您可以通过触发此查询并查看服务器日志来验证它:

The client never really interprets anything you write inside the anonymous function. The server does. The error you see is from the server. You can validate it by firing this query and looking onto the server logs:

2015-12-22T19:03:44.011-0800 I QUERY    [conn1] assertion 16722 ReferenceError:
searc is not defined
    at _funcs1 (_funcs1:1:39) near 's.key === searc){retu'  ns:test.t query:{ $w
here: function (){if(this.key === searc){return true}} }

使用 $ exists operator。

There is a better way to write what you wish to achieve using the $exists operator.

var search = "title";
var find = {};
find[search] = {$exists:true};
db.collection.findOne(find);

这是有效的,因为您在客户端完全构建查询参数,然后再将其传递给 findOne()方法。

This works, because, you build the query parameter fully on the client side, before passing it on to the findOne() method.

这篇关于如何在MongoDB中使用外部变量'where'通过Javascript查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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