我想根据联系人发送或接收的最后消息整理联系人列表。 要做到这一点,我必须对最后的消息(发送和接收)进行排序,添加它们并返回最后一条消息。
我的回答应采用以下格式:
{
"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}
});
我试过这个:
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 :(得分:0)
试试这个
var dateDisplay = new Date( 2016-11-09 05:27:00 UTC );
dateDisplay = dateDisplay.toString()
var arr = (dateDisplay.split(' '))
var date_String = arr[0]+','+arr[1]+' '+arr[2]+' '+arr[3]+','+arr[4]