简体   繁体   English

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

[英]Mongoose: Populate multiple fields on the same path

I have following models: Players, Games and Tournaments In the Game there are always 2 players and a game can have multiple (0-n) reactions.我有以下模型: 玩家、游戏和锦标赛 在游戏中总是有 2 个玩家,一个游戏可以有多个(0-n)反应。

games-Model游戏模型

GameSchema = new Schema({
 players: [{player, scorePoints}]
 reactions: [{player, type}]
})

tournaments-Model锦标赛模型

TournamentSchema= new Schema({
 players: [{player, scorePoints}]
 games: [{game}]
})

in my "GET" Tournament Request, i want to answer with all user-details and need to populate 2 fields from the same "path":在我的“GET”锦标赛请求中,我想回答所有用户详细信息,并需要从同一“路径”填充 2 个字段:

tournament-service比赛服务

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;
}

The Problem is: since it is the same "Path", it will only populate the last field.问题是:由于它是相同的“路径”,它只会填充最后一个字段。 see here: https://mongoosejs.com/docs/populate.html#populating-multiple-paths见这里: https : //mongoosejs.com/docs/populate.html#populating-multiple-paths

eg:例如:

"games:"[{
  players: [
  {"id": "1", "username": "UserOne"},
  {"id": "2", "username": "UserTwo"}
  ],
  reactions: [
   {"id": 1, "type": "angry"}, 
   {"id": 2, "type": "happy"}
 ]
}, 
{ //* next Game*// }
]

How it should be:应该如何:

"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*// }
]

How can i solve this?我该如何解决这个问题?

2 Weeks later, i found a working solution: you can pass an array with all fields to populate: 2 周后,我找到了一个可行的解决方案:您可以传递一个包含所有字段的数组来填充:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM