猫鼬:在同一路径上填充多个字段

Mongoose: Populate multiple fields on the same path

我有以下模型:玩家、游戏和锦标赛 在游戏中总是有 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*// }
]

我该如何解决这个问题?

2 周后,我找到了一个可行的解决方案: 您可以传递一个包含所有字段的数组来填充:

 path: 'games',
 populate: [{
   path: 'players.player',
   select: ['username', 'rating', 'playedGames', 'avatar1']
  }, {
   path: 'reactions.player',
   select: ['username', 'avatar1']
  }]