【问题标题】:Mongoose: Populate multiple fields on the same pathMongoose:在同一路径上填充多个字段
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-03
      • 2020-07-20
      • 2012-01-22
      • 2017-05-21
      • 2015-06-09
      • 1970-01-01
      • 2013-07-06
      • 2021-09-06
      相关资源
      最近更新 更多