【问题标题】:How to use .where() with after a populate in mongoose如何在猫鼬填充后使用 .where()
【发布时间】:2014-03-26 14:36:09
【问题描述】:

所以我有两个模式

var subcategories = new Schema({
    //the category being populated needs to be the same case ;
    categoryId: [{ type: Schema.ObjectId, ref: 'categories' }],
    name: String,
    description:  String,
    display:  Boolean,
    active: Boolean,
    sortOrder:  Number,
    createDate: Date,
    updateDate: Date,
    type:  String,
    startDate: Date,
    endDate: Date,
    authorId: String
});

var categories = new Schema({
    name: String,
    description:  String,
    display:  Boolean,
    active: Boolean,
    sortOrder:  Number,
    createDate: Number,
    updateDate: Number,
    type:  String,
    startDate: Date,
    endDate: Date,
    authorId: String
});

并且我希望只有在类别/子类别中的活动/显示为真时才返回查询。我遇到的问题是如何在填充后正确设置 categoryId 的过滤器。这是我到目前为止所拥有的

exports.generateList = function (req, res) {
    subcategories
            .find({})//grabs all subcategoris
            .where('categoryId').ne([])//filter out the ones that don't have a category
            .populate('categoryId')
            .where('active').equals(true)
            .where('display').equals(true)
            .where('categoryId.active').equals(true)
            .where('display').in('categoryId').equals(true)
            .exec(function (err, data) {
            if (err) {
                console.log(err);
                console.log('error returned');
                res.send(500, { error: 'Failed insert' });
            }

            if (!data) {
                res.send(403, { error: 'Authentication Failed' });
            }

            res.send(200, data);
            console.log('success generate List');
        });
    };

唯一的问题是,即使我有一个 display = false 的类别,它仍然会被返回。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    要为填充引用构建查询条件,可以通过特殊方式引用here

    查询条件和其他选项

    如果我们想根据他们的年龄填充我们的粉丝数组,只选择他们的名字,然后最多返回任意 5 个呢?

    Story
      .find(...)
      .populate({
        path: 'fans',
        match: { age: { $gte: 21 }},
        select: 'name -_id',
        options: { limit: 5 }
    })
    .exec()
    

    所以在你的情况下,你需要做类似的事情:

    subcategories
      .find({})//grabs all subcategoris
      .where('categoryId').ne([])//filter out the ones that don't have a category
      .where('active').equals(true)
      .where('display').equals(true)
      .populate({
        path: 'categoryId',
        match: {
          active: true,
          display: true,
        }
      })
      .exec()
    

    【讨论】:

    • 它非常混乱和稀疏。要获取更多信息,您必须深入了解 API 文档。
    • 现在 mongoDB 使用 join-like $lookup。阅读链接mongoosejs.com/docs/populate.html上的第一行
    • 有什么方法可以过滤填充为空的文档?
    • @moeinrahimi 您的评论将更适合作为一个单独的问题,以便 SO 社区中的其他人可以帮助回答
    猜你喜欢
    • 2017-10-11
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2012-11-11
    • 2015-07-13
    • 2016-10-10
    相关资源
    最近更新 更多