Mongoose - find last message from each user Mongoose - find last message from each user mongoose mongoose

Mongoose - find last message from each user


Use aggregation framework where your pipeline stages have $match, $sort, $group and $project expressions:

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)        }    });

If req.user.username = "admin", with your sample collection then the result is:

{    "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}