Kay*_*Kay 4 mongoose mongodb node.js express mongoose-populate
我想返回所有聊天对话,其中登录用户 (user_id) 是参与者。
我想填充参与者只返回 profile.firstname (以后可能会有其他一些),然后我想过滤掉参与者,以便它不会带回参与者数组中的登录用户(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) { });
Run Code Online (Sandbox Code Playgroud)
聊天模型.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);
Run Code Online (Sandbox Code Playgroud)
根据填充文档,这可以通过“匹配”选项来实现。
在你的情况下,答案是:
Chat.find({participants: user_id})
.populate('participants', {
select: 'profile.firstname',
match: { _id: {$ne: user_id}}
})
.exec(function (err, chats) { });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13490 次 |
| 最近记录: |