2017-09-24 76 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) { });