[英]Mongoosejs - Filter out populate results
我想返回所有聊天對話,其中登錄用戶 (user_id) 是參與者。
我想填充參與者只返回 profile.firstname (以后可能會有其他一些),然后我想過濾掉參與者,以便它不會帶回參與者數組中的 loginUser (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) { });
聊天模型.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);
根據填充文檔,這可以通過“匹配”選項來實現。
在你的情況下,答案是:
Chat.find({participants: user_id})
.populate('participants', {
select: 'profile.firstname',
match: { _id: {$ne: user_id}}
})
.exec(function (err, chats) { });
mongoose populate() 文檔有一些變化。 解決辦法應該是
Chat.find({
participants: user_id
})
.populate({
path: 'participants'
select: 'profile.firstname',
match: {
_id: {
$ne: user_id
}
}
})
.exec(function(err, chats) {});
使用$in此代碼將很有用。
ServiceCategory.find().populate({
path: "services",
match: { zipCodes: {$in: "10400"}},
populate: [
{
path: "offers",
},
],
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.