【问题标题】:Mongoosejs - Filter out populate resultsMongoosejs - 过滤掉填充结果
【发布时间】:2018-03-05 14:55:21
【问题描述】:

我想返回所有聊天对话,其中登录用户 (user_id) 是参与者。

我想填充仅返回 profile.firstname 的参与者(可能稍后会出现其他名称),然后我想过滤掉参与者,以便它不会带回参与者数组中的 loggedInUser (user_id)。

chat.controller.js 索引

 Chat.find({participants: user_id})
            .populate('participants', {
                select: 'profile.firstname',
                where('_id').ne(user_id) // This need to change
            })
            .exec(function (err, chats) { });

chat.model.js

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

let ChatSchema = new Schema({

        participants: [{
            type: Schema.Types.ObjectId, ref: 'User'
        }],

        messages: [{
            type: Schema.Types.ObjectId, ref: 'Message'
        }],

    },
    {
        timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
    });

module.exports = mongoose.model('Chat', ChatSchema);

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-populate


    【解决方案1】:

    根据populate documentation,这可以通过“匹配”选项来实现。

    你的答案是:

    Chat.find({participants: user_id})
            .populate('participants', {
                select: 'profile.firstname',
                match: { _id: {$ne: user_id}}
            })
            .exec(function (err, chats) { });
    

    【讨论】:

      【解决方案2】:

      猫鼬populate() documentation 有一些变化。解决方案应该是

      Chat.find({
              participants: user_id
          })
          .populate({
              path: 'participants'
              select: 'profile.firstname',
              match: {
                  _id: {
                      $ne: user_id
                  }
              }
          })
          .exec(function(err, chats) {});
      

      【讨论】:

        【解决方案3】:

        使用 $in,此代码将很有用。

        ServiceCategory.find().populate({
            path: "services",
            match: { zipCodes: {$in: "10400"}},
            populate: [
                {
                    path: "offers",
                },
            ],
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-08
          • 2014-08-02
          • 1970-01-01
          • 2017-08-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多