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

现在我想根据通过 req.query

传递给控制器​​的一些参数有条件地填充或不填充 categorysubCategorysubSubCategory
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 函数 returns Query 实例,可用于管道新函数:

When a callback function is passed, the operation will be executed immediately with the results passed to the callback. When it is not passed, an instance of Query is returned, which provides a special query builder interface.

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