node.js - 使用 mongoose 根据条件 mongodb 填充或不填充

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

现在我想根据通过 req.query 传递给 Controller ​​的一些参数有条件地填充或不填充 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 函数返回 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/

相关文章:

javascript - Passport.js 用户登录和身份验证

node.js - Mongoose - PUT 请求上的 .save() 错误

node.js - 缺少架构错误 : Schema hasn't been registered for model "Emp"

javascript - Debowerify 无法与 Grunt 一起使用

javascript - 拦截 WebSocket 消息

javascript - 存储密码以登录到 3rd 方 API

node.js - nodejs : where session stores? 什么是connect-mongo?

javascript - Passport 和 express 的基本认证

javascript - 一个 Promise 对多个 Promise - 并发问题

node.js - Mongoose:对 $skip 和 $limit 之后的所有字段数求和