我有一个JSON,其中包含一些过滤条件,如
{
{
field: 'estimatedTime',
operator: '<='
value: '50'
},
{
field: 'message',
operator: 'contains'
value: 'meow'
},
...
}
我在查询中正确翻译
{'$ elemMatch':{'估计时间':{'$ lte':50},'消息':{'$ regex':'meow'}}}
我正在使用elemMatch,因为查询需要在带有嵌套数组的JSON上运行。我们称这个数组字段为'properties'。 我在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.find({'_id': new ObjectId('599ea4b7b924bf16409c67cc'), 'properties': {'$elemMatch': { 'estimatedTime': {'$lte': 50}, 'message': {'$regex': 'meow'}}}}, function (err, person) ...
console.log(“主题:”+人物)打印出我要找的内容。
我做错了什么?感谢。
答案 0 :(得分:0)
@JackLametta这里发生的是
与普通语句和“JSON.parse”相比,数据库查询总是很慢,因此当您使用criteria
并在数据库中写入查询时,我们将拥有新标准&#39;。
所以你可以使用这种方法。
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。