mongoose – 从每个用户find最后一条消息

我正在处理消息系统,我需要从发送消息给login用户的每个用户获取最后一条消息。 我在mongoDB中有这样的结构:

[{ "_id": "551bd621bb5895e4109bc3ce", "from": "admin", "to": "user1", "message": "message1", "created": "2015-04-01T11:27:29.671Z" }, { "_id": "551bd9acf26208ac1d9b831d", "from": "user1", "to": "admin", "message": "message2", "created": "2015-04-01T11:42:36.936Z" }, { "_id": "551bdd6d849d53001dd8a64a", "from": "user1", "to": "user2", "message": "message3", "created": "2015-04-01T11:58:37.858Z" }, { "_id": "551bdd99849d53001dd8a64b", "from": "user2", "to": "admin", "__v": 0, "message": "message4", "created": "2015-04-01T11:59:21.005Z" }, { "_id": "551bdda1849d53001dd8a64c", "from": "user1", "to": "admin", "__v": 0, "message": "message5", "created": "2015-04-01T11:59:29.971Z" }] 

我需要from发送消息给login用户的每个用户的最后一条消息中获取message字段。 我尝试使用不同,但它只返回一个字段。 我有这个:

 Message.find({ to: req.user.username }) .select('message created') .sort('-created') .exec(function (err, messages) { if (err) { return res.status(400).send({ message: getErrorMessage(err) }); } else { res.json(messages) } }); 

但它返回所有发送消息的用户login用户,我需要只有唯一的用户和他们的最后一条消息。 有什么方法如何与mongoose做到这一点?

       

网上收集的解决方案 "mongoose – 从每个用户find最后一条消息"

在stream水线阶段使用$match$sort$group$projectexpression式的地方使用聚合框架:

 Message.aggregate( [ // Matching pipeline, similar to find { "$match": { "to": req.user.username } }, // Sorting pipeline { "$sort": { "created": -1 } }, // Grouping pipeline { "$group": { "_id": "$from", "message": { "$first": "$message" }, "created": { "$first": "$created" } } }, // Project pipeline, similar to select { "$project": { "_id": 0, "from": "$_id", "message": 1, "created": 1 } } ], function(err, messages) { // Result is an array of documents if (err) { return res.status(400).send({ message: getErrorMessage(err) }); } else { res.json(messages) } } ); 

如果req.user.username = "admin" ,那么你的样本集合就是:

 { "result" : [ { "message" : "message4", "created" : "2015-04-01T11:59:21.005Z", "from" : "user2" }, { "message" : "message5", "created" : "2015-04-01T11:59:29.971Z", "from" : "user1" } ], "ok" : 1 }