2017-09-24 70 views
0

我想返回所有聊天对话,其中登录用户(user_id)是参与者。Mongoosejs - 过滤出填充结果

我想填充参与者只返回profile.firstname(可能其他一些版本),然后,我想筛选出参与者,使其不参加阵列中带回是loggedInUser(USER_ID)。

chat.controller.js INDEX

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

回答

0

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

在你的情况下的答案是:

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