【问题标题】:Mongoose - Add 'is_self' field in aggregateMongoose - 合计添加“is_self”字段
【发布时间】:2015-07-26 20:27:36
【问题描述】:

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

编辑: 'is_self' 字段包含一个布尔值,表示消息是否来自用户。

太假了:

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 date...

所以它看起来像这样:

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 不允许这样做..

谢谢!

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    返回布尔值的$eq 运算符的简单用法。此外,$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" 
                      }
                    ]
                }
            }
        }}
    

    【讨论】:

    • 你成功了!我没有意识到 $push 可以以这种方式使用。这也节省了使用 $group 2 次。谢谢
    • @DutchKev 你可能还注意到你过度使用了$and。所有查询参数都是隐含的$and 表达式(除非另有说明),因此通过了解这一点,您的生活会变得更轻松。少打字等等。此外,$$ROOT 并没有按照您的想法行事。它只是流水线阶段“当前”文档的占位符变量。您似乎认为这意味着“原始”文档状态。但这并不意味着。
    • 少打字总是好的!谢谢。我确实发现我误判了$$ROOT。感谢您的提醒
    • @DutchKev 我从不喜欢这个命名并且个人觉得它具有误导性。还有$$CURRENT,这是同一件事,并且文档对于两者之间的区别或区别甚至意味着什么是“错误的”。不是第一个被误导的。通过您注释掉的代码部分,您可能会遇到另一个问题。但是先看看你学到了什么,然后尝试一些事情。
    • 你比我领先 1 步:p 事实上,我也与管道中的用户群(评论部分)斗争。但我的“星期天”勇气告诉我,我可以解决通过部分实现与您的出色答案中给出的相同结构来解决这个问题。我会弄清楚的,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多