【问题标题】:Dynamic MongoDB query动态 MongoDB 查询
【发布时间】:2017-08-24 22:41:27
【问题描述】:

我有一个 JSON,其中包含一些过滤条件,例如

{
    {
       field: 'estimatedTime',
       operator: '<='
       value: '50'
    },
    {
       field: 'message',
       operator: 'contains'
       value: 'meow'
    },
    ...
}

我在查询中正确翻译了它

{'$elemMatch': { 'estimatedTime': {'$lte': 50}, 'message': {'$regex': 'meow'}}}

我正在使用 elemMatch,因为查询需要在带有嵌套数组的 JSON 上运行。我们称该数组字段为“属性”。 我在 MongoDB 上启动了查询,它运行良好。

问题是当我在 Node.js 中使用查询时

users_with_filters.forEach(function(value) {
                console.log(res.id);
                var criteria = {};
                criteria['$elemMatch'] = JSON.parse(value.filter[0].filter).criteria;
                console.log(criteria);
                Topic.find({'_id': new ObjectId('599ea4b7b924bf16409c67cc'), 'properties': criteria}, function (err, person) {
                    if (err) {
                        console.log(err);           
                        //return res.send(err);
                    }
                    console.log("Topic: " + person)
                });
            })

console.log("Topic: " + person) 什么也不打印。

如果我对查询进行硬编码,例如:

Topic.find({'_id': new ObjectId('599ea4b7b924bf16409c67cc'), 'properties': {'$elemMatch': { 'estimatedTime': {'$lte': 50}, 'message': {'$regex': 'meow'}}}}, function (err, person) ...

console.log("Topic: " + person) 打印我要查找的内容。

我做错了什么?谢谢。

【问题讨论】:

    标签: arrays json node.js mongodb


    【解决方案1】:

    @JackLametta 这里发生的事情是

    与普通语句和“JSON.parse”相比,数据库查询总是很慢,因此当您使用criteria 并将查询写入数据库时​​,我们将有一个新的“标准”。

    所以你可以使用这种方法。

     users_with_filters.forEach(function(value) {
                    console.log(res.id);
                 someone(JSON.parse(value.filter[0].filter ).criteria);
                })
     function someone(data){
         var criteria = {};
                    criteria['$elemMatch'] = data;
                    console.log(criteria);
                    Topic.find({'_id': new ObjectId('599ea4b7b924bf16409c67cc'), 'properties': criteria}, function (err, person) {
                        if (err) {
                            console.log(err);           
                            //return res.send(err);
                        }
                        console.log("Topic: " + person)
                    });
    
     }
    

    或者使用 promise 和 async 代替 foreach。

    【讨论】:

    • 打印 console.log(criteria);在我的方法中
    猜你喜欢
    • 2017-02-20
    • 2015-04-09
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多