[英]Query nested property in Mongoose (without dot notation)
I am trying to query MongoDB using Mongoose to find documents based on the value of a nested property. 我正在尝试使用Mongoose查询MongoDB,以基于嵌套属性的值查找文档。
var Obj = new mongoose.Schema({
mainProperty: {
nestedProp1: String
nestedProp2:String
}
})
Due to the way the data is received, I need to perform the query without dot notation (as seen below). 由于接收数据的方式,我需要在不使用点符号的情况下执行查询(如下所示)。
Obj.find({'mainProperty.nestedProp': 'value'})
The code above will get me the correct results, but I need to pass in the query conditions in the format below. 上面的代码将为我提供正确的结果,但我需要以以下格式传递查询条件。
Obj.find({ mainProperty: { nestedProp1: 'value' } })
I'm passing in the entire query object as an argument from on the client side, rather than developing the query on the server. 我将整个查询对象作为参数从客户端传递过来,而不是在服务器上开发查询。 By the time it hits the server, the code above appears as seen below.
当它到达服务器时,上面的代码如下所示。
Obj.find(queryCondition)
//queryCondition holds a value of { mainProperty: { nestedProp1: 'value' } }
Since there are two properties nested within mainProperty, it is not valid to perform the search above. 由于在mainProperty中嵌套了两个属性,因此执行上面的搜索无效。 It will search for documents that have mainProperty equal exactly to what is passed in following the colon (meaning documents that have a value equal to nestedProp1 and do not have a nestedProp2).
它将搜索mainProperty完全等于冒号后传递的文档(意味着其值等于nestedProp1且没有nestedProp2的文档)。
Is there another way to call this (without dot notation or editing the object itself) where it will query for the value of nestedProp1 rather than the value of mainProperty? 还有另一种方法来调用此方法(无需点符号或编辑对象本身),在此方法中它将查询nestedProp1的值而不是mainProperty的值?
There is, you could do something like 有,你可以做类似的事情
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 );
So if you have specified the filter, you will receive filtered records, otherwise the default records. 因此,如果您指定了过滤器,您将收到过滤的记录,否则将接收默认记录。
I haven't tested the code, so if this doesn't work you can try doing filter['mainProperty']['nestedProp1'] = req.body.nestedProp1;
我还没有测试代码,所以如果这不起作用,您可以尝试执行
filter['mainProperty']['nestedProp1'] = req.body.nestedProp1;
You can use most Mongo DB syntax with Mongoose find()
. 您可以将大多数Mongo DB语法与Mongoose
find()
。 Try this: 尝试这个:
Obj.find({ mainProperty: { nestedProp1: { $in: ['value'] } } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.