Utilisez le cadre d'agrégation où vos étapes de pipeline ont $match
, $sort
, $group
et $project
expression :
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)
}
}
);
Si req.user.username = "admin"
, avec votre collection d'échantillons, le résultat est :
{
"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
}