如何使用另一个子文档中的数据填充 Mongoose 子文档
How to populate Mongoose subdocument with data from another subdocument
我有一个 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
}
]
]
}
您可以在 Mongoose 的 population 路径中使用点符号来指定要填充的子文档层次结构中的路径:
Club.findOne().populate('seasons.seasonPlayers.player').exec(function(err, club) {...});
我有一个 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
}
]
]
}
您可以在 Mongoose 的 population 路径中使用点符号来指定要填充的子文档层次结构中的路径:
Club.findOne().populate('seasons.seasonPlayers.player').exec(function(err, club) {...});