I have a document which has a field as Array of References and it is refering to the same document. I want to populate all the nested fields.
The Data will be Acyclic (person -> children -> children ≠ person).
The Schema of the Document look like
const personSchema = new mongoose.schema({
name: {
type: String,
required: true,
},
[...],
children: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Person",
}],
});
const Person = mongoose.model("Person", personSchema);
while finding a person with his/her _id I want that it’s children, children’s children, …. must be populated
Output should look like
{
"_id": 1,
"name": "John Doe",
"children": [
{
"_id": 2,
"name": "Jane Doe",
"children": [
{
"_id": 3,
"name": "Billy Doe",
"children": [
{
"_id": 4,
"name": "Bobby Doe"
[...]
}
]
}
]
}
]
}
2
Answers
Try this recursive function.
Mongoose lets you add
pre
andpost
hooks as part of their middleware.By adding a
pre
hook to thefind
middleware you can tell mongoose to alwayspopulate
thechildren
property and will do so recursively. However, since you only want thepopulate
to happen when a user is searching by_id
you need a condition. In the mongooseQuery
object there is a property called_conditions
whose value is an object. So if that object has the_id
property you know you are searching using the_id
and therefore it won’tpopulate
on any of the otherfind
calls e.g. searching byname
etc.Based on your schema and
_id
property it would look like this: