Pradeep Parmar
Pradeep Parmar

Reputation: 41

Mongoose aggregate Get sum of likes in multiple records from another collection

I need to get the sum of count of likes field from all posts of the user
Here is the schema
user schema


    {
        "_id": "5f5b784209393b0638f896e2",
        "name": "Test User",
        "avatar": "https://someurl/attachments/media-6489.PNG"
    }

posts schema


    {
        "likes": [
            "5f4d553370eef30017288fb0",    // other users who liked the post
            "5f4fad6cc7d4990017fb0d29",
            "5f5a3c074de2d1246c99767b",
            "5f5b790532dd2f1de4127aa4",
            "5f5c6aeff8170922d44eeb7a"
        ],
        "_id": "5f65daf13ce59d0a5482ea0d",
        "text": "fdsa",
        "author": "5f5b784209393b0638f896e2",
    }

i'm new to mongoose, thanks in advance..

Upvotes: 0

Views: 248

Answers (1)

Pradeep Parmar
Pradeep Parmar

Reputation: 41

finally got this query doing what's required

const postsData = await User.aggregate([
    { $match: { _id: mongoose.Types.ObjectId(req.user.id) } },
    {
        $lookup: {
            from: "posts",
            localField: "_id",
            foreignField: "author",
            as: "posts",
        }
    },
    { $unwind: "$posts", },
    {
        $group: {
            _id: "$_id",
            likes: { $sum: { $size: "$posts.likes" } }
        }
    },
]);

Upvotes: 0

Related Questions