gpt4 book ai didi

node.js - Mongoose - 聚合添加 'is_self' 字段

转载 作者:可可西里 更新时间:2023-11-01 10:28:02 26 4
gpt4 key购买 nike

我正在构建一个聊天应用程序,它应该从 MongoDB 检索所有新消息,并分组到对话中。但是每条消息都应该有一个新的“is_self”字段

编辑:“is_self”字段包含一个 bool 值,表示消息是否来自用户。

如此伪:

is_self: {$cond: {if: {message.sender == MYID)}, then: true, else: false}

假设我有消息模型

    var MessageSchema  = new Schema({
conversation_id:{type: mongoose.Schema.ObjectId, ref: 'Conversation', required: true},
message: {type: String, required: true},
sender: {type: mongoose.Schema.ObjectId, ref: 'User'},
created: {type: Date, default: Date.now},
read: {type: Boolean, default: false}
});

还有一个对话模型

    var ConversationSchema = new Schema({
from: {type: mongoose.Schema.ObjectId, ref: 'User', required: true},
to: {type: mongoose.Schema.ObjectId, ref: 'User', required: true},
last_changed: {type: Date, default: Date.now},
created: {type: Date, default: Date.now}
});

现在我尝试进行聚合,以加载 conversation_id 数组中的所有消息并创建 > last_checked 日期...

所以看起来像这样:

mongoose.model("Message").aggregate([
// First find all messages
{
$match: {
$and: [{conversation_id: {$in: idArray}}, {created: {$gt: lastChecked}}]
}
},
// Add is self field
{
$group: {
_id: $_id,
$is_self: {
$cond: {'if(message.sender == MYID then true else false': '??'}
}
}
},
// Sort by date
{$sort: {created: -1}},

// Then group by conversation
{
$group: {
_id: '$conversation_id',
messages: {
$push: '$$ROOT'
},

}
}
// TODO: find users for unknown conversation
/*,
{
$project: {
user: {
$or: [{conversation_id: {$in: knownConversations}}]
}
}
}*/
])

我尝试使用 $cond 和 if/else 语句,但 Mongo 不允许这样......

谢谢!

最佳答案

$eq 的简单用法返回 bool 值的运算符。还有 $push将采用您扔给它的任何对象格式:

var senderId = // whatever;

mongooose.model("Message").aggregate([
{ "$match": {
"conversation_id": { "$in": idArray },
"created": { "$gt": lastChecked }
}},
{ "$group": {
"_id": "$conversation_id",
"messages": {
"$push": {
"message": "$message",
"is_self": {
"$eq": [ "$sender", senderId ]
}
}
}
}}
// whatever else
],function(err,results) {

})

如果你想要,然后结合 $cond仅在检测到时交替添加“is_self”:

    { "$group": {
"_id": "$conversation_id",
"messages": {
"$push": {
"$cond": [
{ "$eq": [ "$sender", senderId] },
{
"message": "$message",
"is_self": true
},
{
"messsage": "$message"
}
]
}
}
}}

关于node.js - Mongoose - 聚合添加 'is_self' 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com