我有两种模式:比赛和赞。他们之间有一对多的关系。现在我想检索所有比赛,如果在Like表中有一行,则为每个比赛添加一个 isLiked 属性。
这是竞争模型查询和结果:
查询:
Competition.find().lean().exec(function (err, competitions) {
if (err) {
console.log(err);
}
else {
res.json(competitions);
}
});
结果:
[
{
"_id": "5b0a677ab8ceab2132a6491e",
"mediaType": "MOV",
"isScoreViewable": true,
"title": "Liverpool vs RealMadrid",
"__v": 0
},
...
]
我想要这样的事情:
[
{
"_id": "5b0a677ab8ceab2132a6491e",
"mediaType": "MOV",
"isScoreViewable": true,
"title": "Liverpool vs RealMadrid",
"__v": 0,
"isLiked": true <=== Must be add
},
...
]
我尝试了以下代码,但 isLiked 属性未添加到结果中:
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);
}
});