【问题标题】:Populate or not based on a condition mongodb using mongoose使用 mongoose 根据条件 mongodb 填充或不填充
【发布时间】:2016-08-06 13:50:58
【问题描述】:

我在猫鼬中有以下架构,

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)

如何实现?

【问题讨论】:

    标签: node.js express mongoose mean-stack


    【解决方案1】:

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

    【讨论】:

    • 太棒了。我认为这应该是query = query..populate('subCategory');query = query..populate('subSubCategory'); @Alexander Mac 中的一个点谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2019-01-31
    • 2015-08-07
    • 2020-10-14
    • 2020-09-06
    • 2021-06-04
    • 2020-12-22
    相关资源
    最近更新 更多