0

I have two models: Competition and Like. there is an one-to-many relationship between them. Now I want to retrieve all competitions and add one property isLiked to each of competitions if there is a row in Like table.

This is competition model query and result :

Query:

Competition.find().lean().exec(function (err, competitions) {
    if (err) {
        console.log(err);
    }
    else {
        res.json(competitions);
    }
});

Result:

[
    {
        "_id": "5b0a677ab8ceab2132a6491e",
        "mediaType": "MOV",
        "isScoreViewable": true,
        "title": "Liverpool vs RealMadrid",
        "__v": 0
    },
     ...
]

and I want something like this:

[
    {
        "_id": "5b0a677ab8ceab2132a6491e",
        "mediaType": "MOV",
        "isScoreViewable": true,
        "title": "Liverpool vs RealMadrid",
        "__v": 0,
        "isLiked": true <=== Must be add
    },
     ...
]

I tried below code but isLiked property doesn't add to result:

Coin.find().lean().exec(function (err, competitions) {
    if (err) {
        console.log(err);
    }
    else {
        Like.find({ iid: req.params.id }).lean().exec(function (err, likes) {
            if (err) {
                console.log(err);
            }
            else {
                competitions.forEach(function(competition) {
                    likes.forEach(function(like) {
                        competition.isLiked = like.competition_id == competition._id;
                    });
                });
            }
        });
        return res.json(competitions);
    }
});
Mahmood Kohansal
  • 1,021
  • 2
  • 16
  • 42

0 Answers0