繁体   English   中英

使用mongoose基于mongodb的条件填充或不填充

[英]Populate or not based on a condition mongodb using mongoose

我在猫鼬中有以下架构,

Schema = new Schema({
    category = { type: Schema.Types.ObjectId, ref: 'Category' },
    subCategory = { type: Schema.Types.ObjectId, ref: 'subCategory' },
    subSubCategory = { type: Schema.Types.ObjectId, ref: 'subSubCategory' },
    name: String
});

现在我想有条件地填充或不categorysubCategorysubSubCategory基础上,通过传递给控制器的几个参数req.query

Schema.find(function(err, data) {
   if(err) { //handle errors }
   if(!data) { //throw 404 }
   res.status(200).json(data); 
})
.populate('category') //execute only if(req.query.populateCategory == true)
.populate('subCategory') //execute only if(req.query.populateSubCategory == true)
.populate('subSubCategory'); //execute only if(req.query.populateSubSubCategory == true)

怎么能实现呢?

Mongoose模型find函数返回Query实例,您可以使用它来管道新函数:

传递回调函数时,将立即执行操作,并将结果传递给回调。 如果未传递,则返回Query实例,该实例提供特殊的查询构建器接口。

var query = Schema.find({}); // TODO: add filter

if (req.query.populateCategory == true) {
    query = query.populate('category');
}
if (req.query.populateSubCategory == true) {
    query = query.populate('subCategory');
}
if (req.query.populateSubSubCategory == true) {
    query = query.populate('subSubCategory');
}

query.exec(function(err, data) {
    if (err) { //handle errors }
    if (!data) { //throw 404 }
    res.status(200).json(data); 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM