查询mongoose获取每个对话的最后一条消息

时间:2015-10-26 02:31:04

标签: node.js mongodb mongoose

我有模特聊天:

var schema = mongoose.Schema({
   userSend:        {type: ObjectId, ref: 'User' },
   userReceive:         {type: ObjectId, ref: 'User' },
   message :        {type: 'String', require: true},
   status:          {type: 'Boolean', default: true}, 
   time:            {type: 'Date', default: Date.now}
}); 
module.exports = mongoose.model('Chat', schema);

PLS!帮我查询以获得彼此的最后一条消息。与facebook对话相同。

它是样本数据

{_id: '156478', msg: 'Hello lam', userSend: 'ZungX', userReceive:'Lam', timestamp: '2015-10-25T18:02:41.400Z'}
{_id: '586456', msg: 'hi My', userSend: 'Duc', userReceive:'My', timestamp: '2015-10-25T19:05:00.400Z'}
{_id: '254566', msg: 'Hello Duc', userSend: 'ZungX', userReceive:'Duc', timestamp: '2015-10-26T13:06:41.400Z'} 
{_id: '456899', msg: 'hi ZungX last', userSend: 'Duc', userReceive:'ZungX', timestamp: '2015-10-26T17:02:41.400Z'}
{_id: '987556', msg: 'Hello ZungX', userSend: 'Lam', userReceive:'ZungX', timestamp: '2015-10-26T20:01:41.400Z'}
{_id: '456878', msg: 'Chao Lam', userSend: 'ZungX', userReceive:'Lam', timestamp: '2015-10-26T21:54:21.400Z'} 

现在,我希望得到用户'ZungX'的列表对话

我想要这个结果:

[
    {   
        msg:        'hi ZungX last',
        withUser:   'Duc', //it's userSend
        timestamp:  '2015-10-26T17:02:41.400Z'
    },
    {
        msg:        'Chao Lam',
        withUser:   'Lam', //it's userReceive
        timestamp:  '2015-10-26T21:54:21.400Z'
    }
]

我有搜索相同的问题,但我不明白

谢谢大家:D

'嗨ZungX最后'这是'ZungX'与'Duc'的最后一条消息。注意:此消息用户'ZungX'的角色为 UserReceive

'Chao Lam'是'ZungX'与'Lam'的最后一条消息。注意:此消息用户'ZungX'的角色为 UserSend

2 个答案:

答案 0 :(得分:0)

使用 aggregation framework 获取所需结果,如以下示例所示:

var pipeline = [
    {
        "$match": {
            "userReceive": "ZungX"
        }
    },
    {
        "$project": {
            "msg": 1, "withUser": "$userSend", "timestamp": 1, "_id": 0
        }
    }
]

Chat.aggregate(pipeline)
    .exec(function(err, results){
        // handle err
        console.log(results);
    });

// Or use the aggregation pipeline builder for a more fluent call
Chat.aggregate()
    .match({ "userReceive": "ZungX" })
    .project({ "msg": 1, "withUser": "$userSend", "timestamp": 1, "_id": 0 })
    .exec(function(err, results){
        // handle err
        console.log(results);
    });

答案 1 :(得分:0)

我正在努力解决这个确切的问题 - 显示一个与“从”和“到”字段的对话列表。 在您的情况下,您可以执行类似于以下的汇总:

aggregate(
  [
    { $match: {$or: [{from: USERNAME}, {to: USERNAME}]}},
    { $project: {...FIELDS}},
    { $sort: { timestamp: -1} },
    {
      $group: {
        _id: {$concat: [{$userSend}, {$userReceive}]},
        userSend : {$first: '$from'},
        userReceive: {$first: '$to'},
        msg: {$first: '$msg'},
        timestamp: {$first: '$timestamp'}
      }
    }
  ]
)

如果像我一样,你的“userSend”和“userReceive”字段不是普通字符串(比如ObjectIds),那么最好添加一个“conversationId”字段保存为:

Chat.conversationId = [Receiver._id, Sender._id].sort().join('.')