Mongoose - find last message from each user

前端 未结 1 1420
栀梦
栀梦 2021-01-05 07:23

I\'m working on message system and I need to get last message from each user who sent message to logged user. I have this structure in mongoDB:

[{
    \"_id\         


        
相关标签:
1条回答
  • 2021-01-05 07:52

    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
    }
    
    0 讨论(0)
提交回复
热议问题