我有一个文档,其中有一个字段作为引用数组,并且它引用同一个文档。我想填充所有嵌套字段。
数据将是非循环的(人 -> 儿童 -> 儿童 ≠ 人)。
文档的架构如下
const personSchema = new mongoose.schema({
name: {
type: String,
required: true,
},
[...],
children: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Person",
}],
});
const Person = mongoose.model("Person", personSchema);
在寻找具有他/她的_id的人时,我希望它是孩子,孩子的孩子,....必须填充
输出应如下所示
{
"_id": 1,
"name": "John Doe",
"children": [
{
"_id": 2,
"name": "Jane Doe",
"children": [
{
"_id": 3,
"name": "Billy Doe",
"children": [
{
"_id": 4,
"name": "Bobby Doe"
[...]
}
]
}
]
}
]
}
尝试这个递归函数。
populateChildrenRecursively = async function() {
await this.personSchema.populate('children').execPopulate();
for (let child of this.children) {
await child.populateChildrenRecursively();
}
};