0

我想根據從聯繫人發送或接收的最後一條消息來組合一個聯繫人列表。 要做到這一點,我必須排序最後的消息(發送和接收),添加它們並返回最後一個。貓鼬尋找由兩個字段分組的最後郵件

我的反應應該是在以下格式:

{ 
    "success": true, 
    "chatlist": [ 
    { 
     "id_user": "54228fe2c0df8d1120ed091b", 
     "lastMessage": { 
     "content": "message 6", 
     "date": "2016-11-09T02:54:41.687Z" 
     }, 
     "unreadMessages": 3, 
     "name": "user 1" 
    }, 
    { 
     "id_user": "12228fe2c0df8d11204g4d", 
     "lastMessage": { 
     "content": "message 3", 
     "date": "2016-11-09T02:54:23.329Z" 
     }, 
     "unreadMessages": 2, 
     "name": "user 2" 
    }, 
    { 
     "id_user": "58228fe2c0df8d1120e12sd", 
     "lastMessage": { 
     "content": "message 1", 
     "date": "2016-11-09T02:54:19.313Z" 
     }, 
     "unreadMessages": 1, 
     "name": "user 3" 
    } 
    ], 
    "pages": 2 
} 

我的用戶架構是:

var schema = new Schema({ 
    name: {type: String, required: true}, 
    email: {type: String, required: true, unique: true}, 
    password: {type: String, required: true, select: false}, 
    created_at: {type: Date, required: true, default: Date.now} 
}); 

我的信息模式是:

var schema = new Schema({ 
    content: {type: String, required: true}, 
    type: {type: String, required: true, default: 'text'}, 
    status: {type: String, default: 'not_read'}, 
    created_at: {type: Date, default: Date.now}, 
    read_at: {type: Date}, 
    userFrom: {type: Schema.Types.ObjectId, ref: 'User', required: true}, 
    userTo: {type: Schema.Types.ObjectId, ref: 'User', required: true} 
}); 

我已經tryed此:

var itensPerPage = 15; 
var skip = page !== undefined ? page * itensPerPage : 0; 
pages = Math.ceil(pages/itensPerPage); 

Message 
.aggregate([ 
    { '$sort': { 
     'created_at': -1 
    }}, 
    { "$skip": skip }, 
    { "$limit": itensPerPage }, 
    { '$match': { 
     $or: [ 
      { userFrom: user.id_user }, 
      { userTo: user.id_user } 
     ] 
    }}, 
    { '$group': { 
      '_id': { 
       'userFrom': '$userFrom', 
       'userTo': '$userTo' 
      }, 
     } 
    }, 
]) 
.exec(function (err, messages) { 
    res.send({"success": true, "chatlist": messages, "pages": pages}); 
}); 

如何修改我的查詢以獲得所需的響應? 謝謝。

回答

0

試試這個

var itensPerPage = 15; 
var skip = page !== undefined ? page * itensPerPage : 0; 
pages = Math.ceil(pages/itensPerPage); 

Message 
.aggregate([ 
    { '$sort': { 
     'created_at': -1 
    }}, 
    { "$skip": skip }, 
    { "$limit": itensPerPage }, 
    { '$match': { 
     $or: [ 
      { userFrom: user.id_user }, 
      { userTo: user.id_user } 
     ] 
    }}, 
{$unwind : $chatlist}, 
{$sort : {chatlist.date : -1}}, 
{$group : {_id : $_id},chatlist : {$push : $chatlist}}, 
]) 
.exec(function (err, messages) { 
    res.send({"success": true, "chatlist": messages, "pages": pages}); 
}); 
+0

我得到了錯誤: 「錯誤:參數必須是總管道運營商」 – Renan