我在 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
传递给 Controller 的一些参数有条件地填充或不填充 category
、subCategory
、subSubCategory
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
实例,您可以使用它来管道新函数:
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);
});
关于node.js - 使用 mongoose 根据条件 mongodb 填充或不填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36632755/