2016-01-08 79 views
0

我有一个包含有关足球俱乐部的数据的MongoDB数据库。俱乐部有球员和季节。一名球员每个赛季可以有不同的球队号码。如何使用另一个子文档中的数据填充Mongoose子文档

考虑以下猫鼬模式:

const clubSchema = new mongoose.Schema({ 
    players: [playerSchema], 
    seasons: [seasonSchema] 
}); 

const personSchema = new mongoose.Schema({ 
    firstName: String, 
    lastName: String 
}); 

const playerSchema = new mongoose.Schema({ 
    person: personSchema, 
    picture: String 
}); 

const seasonSchema = new mongoose.Schema({ 
    name: String, 
    seasonPlayers: [seasonPlayerSchema] 
}); 

const seasonPlayerSchema = new mongoose.Schema({ 
    player: { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: "Player" 
    }, 
    squadNumber: Number 
}); 

如何取回完全填充Club文件?因此,与其让这样的事情:

{ 
    players: [ 
    { 
     _id: ObjectId("abc123"), 
     person: { 
     firstName: "John", 
     lastName: "Doe" 
     } 
     picture: "john.jpg" 
    } 
    ], 
    seasons: [ 
    name: "2015-2016", 
    seasonPlayers: [ 
     { 
     player: ObjectId("abc123"), 
     squadNumber: 10 
     } 
    ] 
    ] 
} 

我想是这样的:

{ 
    players: [ 
    { 
     _id: ObjectId("abc123"), 
     person: { 
     firstName: "John", 
     lastName: "Doe" 
     } 
     picture: "john.jpg" 
    } 
    ], 
    seasons: [ 
    name: "2015-2016", 
    seasonPlayers: [ 
     { 
     player: { 
      person: { 
      firstName: "John", 
      lastName: "Doe" 
      } 
      picture: "john.jpg" 
     }, 
     squadNumber: 10 
     } 
    ] 
    ] 
} 

回答

0

您可以使用点符号在猫鼬的population路径来指定子文档层次结构中的路径来填充:

Club.findOne().populate('seasons.seasonPlayers.player').exec(function(err, club) {...}); 
+0

我试过,但'player'得到的值为'null' – Korneel

+0

@Korneel“playerSchema”是否只嵌入在俱乐部文档中,而不是在其自己的模型/集合中? – JohnnyHK

+0

的确,只有嵌入,不在其自己的集合 – Korneel

相关问题