我在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
subCategory
,subSubCategory
,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)
如何实现?
答案 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);
});