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

时间:2016-04-14 19:55:41

标签: node.js express mongoose mean-stack

我在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
});

现在我想根据通过category

传递给控制器​​的一些参数来有条件地填充或不填充subCategorysubSubCategoryreq.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)

如何实现?

1 个答案:

答案 0 :(得分:2)

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); 
});