【发布时间】:2021-09-27 13:43:48
【问题描述】:
我有以下模型:玩家、游戏和锦标赛 在游戏中总是有 2 个玩家,一个游戏可以有多个 (0-n) 反应。
游戏模型
GameSchema = new Schema({
players: [{player, scorePoints}]
reactions: [{player, type}]
})
锦标赛模型
TournamentSchema= new Schema({
players: [{player, scorePoints}]
games: [{game}]
})
在我的“GET”锦标赛请求中,我想回答所有用户详细信息,并且需要从同一“路径”填充 2 个字段:
比赛服务
async function getOne(id) {
let tournament = await Tournament.findById(id)
.populate({
path: 'games',
populate: {
path:'players.player',
select: ['username', 'avatar']
}
})
.populate({
path: 'games',
populate: {
path: 'reactions.player',
select: ['username', 'avatar']
}
})
.exec();
return tournament;
}
问题是:因为它是相同的“路径”,它只会填充最后一个字段。 看这里:https://mongoosejs.com/docs/populate.html#populating-multiple-paths
例如:
"games:"[{
players: [
{"id": "1", "username": "UserOne"},
{"id": "2", "username": "UserTwo"}
],
reactions: [
{"id": 1, "type": "angry"},
{"id": 2, "type": "happy"}
]
},
{ //* next Game*// }
]
应该如何:
"games:"[{
players: [
{"id": "1", "username": "UserOne"},
{"id": "2", "username": "UserTwo"}
],
reactions: [
{"id": 1, "username": "UserOne", "type": "angry"},
{"id": 2, , "username": "UserTwo", "type": "happy"}
]
},
{ //* next Game*// }
]
我该如何解决这个问题?
【问题讨论】:
标签: javascript mongoose populate