Mongoose在MongoDB中的每次对话都获取最新消息

时间:2018-10-09 13:23:00

标签: node.js mongodb

具有模型聊天:

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);

请!帮助我查询以获取彼此之间的最后一条消息。与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'} 
Now, i want get list conversation of user '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'
    }
]

我有相同的搜索问题,但我不理解

谢谢

0 个答案:

没有答案