[英]Mongoose find all referenced documents
猫鼬是否提供从先前查询的结果中查找所有参考文档的方法?
例如:
Product
.find(query)
.exec(function(err, results) {
...
Product
.find({
'$or': [
// get all products where _id is in results.associatedProducts[]
]
})
...
});
我无法找到一种方法来用猫鼬进行本机处理,请参见下面的工作解决方案。
Product
.find(query)
.exec(function(err, products) {
...
var associatedSoftware = products.reduce(function(memo, current) {
if(current.features && current.features.associatedSoftware) {
return memo.concat(current.features.associatedSoftware.map(function(item) {
return item._id;
}));
}
return memo;
}, []);
Product.find({
'$or': [
...
{ '_id': { '$in': associatedSoftware } }
...
]
})
.exec(function(err, associated) {
...
});
});
是。
您可以使用查询填充 。
Product
.find(query)
.populate('associatedProducts')
.exec(function(err, results) {
// ...
});
这将返回一个格式如下的对象:
var product = {
foo: bar,
associatedProducts: [
// Here are the associated products
{
// Product Object
},
{
// Product Object
},
{
// Product Object
}
]
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.