i want to create 1 objects nested document like:
Children:
chil1:
{ name: 'Mimi',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e57,
__v: 0 },
chil2
{ name: 'Kiki',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e58,
__v: 0 }
Parent:(What i want)
[ { name: 'John',
_id: 537258f63eb92b3201b65e56,
__v: 0,
children: [ { name: 'Mimi',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e57,
__v: 0 },
Children:[ { name: 'Mimi',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e57,
__v: 0 },
{ name: 'Kiki',
parent: 537258f63eb92b3201b65e56,
_id: 537258f63eb92b3201b65e58,
__v: 0 } ]
is possible to create data on mongooese with nodejs(express)? it is similar this question mongoose: How to insert a single subdocument - not an array but in this case, the children only stored id of child, not all the object ? Here is my model file:
const schema:mongoose.Schema = new mongoose.Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
name: String,
parentCategory: {
type: mongoose.Schema.Types.ObjectId,
ref: 'parent',
},
childCategories: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'child',
}],
});
Normally result :
{ name: 'John',
_id: 537258f63eb92b3201b65e56,
__v: 0,
children: [Chil1_id, Chil2_id]
}
Did you try populate?
Here is a simple example:
Parent.find().populate("children").exec(...)
As long as you specify the children's ref to a model, mongoose is smart enough to join the children with the parents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With