【发布时间】:2014-08-05 07:16:47
【问题描述】:
我将如何更改此存档视图聚合以也聚合 from.view.archive :true?
..同时防止重复消息的聚合..如果 To 数组中存在 From User (sessionUser),则只获取此消息之一..
if (archive === true) {
console.log('archive === ' + true);
Models.Message.aggregate([
// Match documents
{ "$match": {
"to": {
"$elemMatch": {
"username": req.session.username,
"view.archive": true,
"view.bin": false
}
},
"$or": messagingquery
}},
// Unwind to de-normalize
{ "$unwind": "$to" },
// Match the array elements
{ "$match": {
"to.username": req.session.username,
"to.view.archive": true,
"to.view.bin": false
}},
// Group back to the original document
{ "$group": {
"_id": "$_id",
"from": { "$first": "$from" },
"to": { "$push": "$to" },
"message": { "$first": "$message" },
"timesent": { "$first": "$timesent" },
"replies": { "$first": "$replies" },
"messaging": { "$first": "$messaging" }
}},
// Sort by updated, most recent first (descending)
{"$sort": {"updated": -1}}
], function (err, messages) {
if (err) {
console.log(err);
res.send(err);
}
res.json({
messages : messages,
sessionUser: sessionUser
});
});
}
对于 MessageSchema 的 From 和 To 数组,UserMessageSchema 看起来像这样:
var UserMessageSchema = new Schema({
user : { "type": Schema.ObjectId, "ref": "User" },
username : String,
view : {
inbox : Boolean,
outbox : Boolean,
archive : Boolean,
bin : Boolean
},
read : {
marked : { "type": Boolean, default: false },
datetime : Date
},
updated : Date
});
【问题讨论】:
标签: node.js mongodb if-statement mongoose aggregation-framework