[英]Query nested property in Mongoose (without dot notation)
我正在尝试使用Mongoose查询MongoDB,以基于嵌套属性的值查找文档。
var Obj = new mongoose.Schema({
mainProperty: {
nestedProp1: String
nestedProp2:String
}
})
由于接收数据的方式,我需要在不使用点符号的情况下执行查询(如下所示)。
Obj.find({'mainProperty.nestedProp': 'value'})
上面的代码将为我提供正确的结果,但我需要以以下格式传递查询条件。
Obj.find({ mainProperty: { nestedProp1: 'value' } })
我将整个查询对象作为参数从客户端传递过来,而不是在服务器上开发查询。 当它到达服务器时,上面的代码如下所示。
Obj.find(queryCondition)
//queryCondition holds a value of { mainProperty: { nestedProp1: 'value' } }
由于在mainProperty中嵌套了两个属性,因此执行上面的搜索无效。 它将搜索mainProperty完全等于冒号后传递的文档(意味着其值等于nestedProp1且没有nestedProp2的文档)。
还有另一种方法来调用此方法(无需点符号或编辑对象本身),在此方法中它将查询nestedProp1的值而不是mainProperty的值?
有,你可以做类似的事情
const filter = {};
// check if you have specified nestedProp1
if ( req.body.nestedProp1 ) {
filter['mainProperty.nestedProp1'] = req.body.nestedProp1;
}
if ( req.body.nestedProp2 ) {
filter['mainProperty.nestedProp2'] = req.body.nestedProp2;
}
// and then
Obj.find( filter );
因此,如果您指定了过滤器,您将收到过滤的记录,否则将接收默认记录。
我还没有测试代码,所以如果这不起作用,您可以尝试执行filter['mainProperty']['nestedProp1'] = req.body.nestedProp1;
您可以将大多数Mongo DB语法与Mongoose find()
。 尝试这个:
Obj.find({ mainProperty: { nestedProp1: { $in: ['value'] } } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.