const {category, parent} = newCategory;
const newCat = new Category({
_id: new mongoose.Types.ObjectId(),
name: category,
parent: parent
}).save((err, res) => {
if(err) { console.log(err)}
else{
console.log("res in create category:", res);
// io.to(user.room).emit('create-category-to-list', {res});
}
})
In log
res in create category: {
codewords: [],
children: [],
_id: 604916cf866a154e284b2e29,
name: 'nameofasdasdasdcat',
parent: 60490c9ce00e8b7a38cf4752,
path: '60490c9ce00e8b7a38cf4752#604916cf866a154e284b2e29',
_v:0
}
Here the document is created but not assigned to its parent why this is happening.
Here you can see parent children array is empty
root: {
children: [],
_id: 60490c9ce00e8b7a38cf4752,
name: 'root',
path: '60490c9ce00e8b7a38cf4752',
_v:0
}
Here i am using mongoose pulgin(mongoose-mpath) for create a tree form data.
For mongoose-mpath https://www.npmjs.com/package/mongoose-mpath
In getChildrenTree function need to pass options as lean:false
const parent = await Folder.findOne({ _id: user.rootId });
const tree = await parent.getChildrenTree(
{
populate: 'codewords',
options: { lean: false } //you need to pass options as lean: false
});
console.log({ tree });
In log
{
tree: [
{
codewords: [],
children: [],
_id: 604c6c5bc8a2e03ee43c4c7b,
name: 'Category-name-2',
parent: 604c690b87924705a401f9ce,
path: '604c690b87924705a401f9ce#604c6c5bc8a2e03ee43c4c7b',
__v: 0
},
{
codewords: [],
children: [],
_id: 604c6ce2c8a2e03ee43c4c7d,
name: 'Category-name-2',
parent: 604c690b87924705a401f9ce,
path: '604c690b87924705a401f9ce#604c6ce2c8a2e03ee43c4c7d',
__v: 0
},
{
codewords: [],
children: [Array],
_id: 604c6d21c8a2e03ee43c4c7e,
name: 'Category-name-3',
parent: 604c690b87924705a401f9ce,
path: '604c690b87924705a401f9ce#604c6d21c8a2e03ee43c4c7e',
__v: 0
}
]
}
for your better understanding you can check mongoose-mpath github issue section ==> https://github.com/vikpe/mongoose-mpath/issues/10