I'm trying to remove subdocument with ID from Object using Mongoose. I was trying to use update fucntion in Moongose but after i run script Im getting status "Ok: 1" but status "nModified: 0". Was trying to use following script:
Page.update({"subPages._id": req.body.ID}, {"$unset":{"subPages":1}}, function (re,q) {
console.log(q);
});
This script removes all subdocuments from a object. Here is my json:
{
"_id" : ObjectId("585a7a7c2ec07b40ecb093d6"),
"name_en" : "Head Page",
"name_nl" : "Head Page",
"slug_en" : "Head-page",
"slug_nl" : "hoofd-menu",
"content_en" : "<p>Easy (and free!) You should check out our premium features.</p>",
"content_nl" : "<p>Easy (and free!) You should check out our premium features.</p>",
"date" : ISODate("2016-12-21T12:50:04.374Z"),
"is_footerMenu" : 0,
"is_headMenu" : 0,
"visible" : 1,
"__v" : 0,
"subPages" : [
{
"content_nl" : "<p>Easy (and free!) You should check out our premium features.</p>",
"content_en" : "<p>Easy (and free!) You should check out our premium features.</p>",
"slug_nl" : "Sub-page",
"slug_en" : "Sub-page",
"name_nl" : "Subpage",
"name_en" : "Subpage",
"date" : ISODate("2016-12-21T14:58:44.733Z"),
"subPages" : [],
"is_footerMenu" : 0,
"is_headMenu" : 0,
"visible" : 1,
"_id" : ObjectId("585a98a46f657b52489087a8")
},
{
"content_nl" : "<p>Easy (and free!) You should check out our premium features.</p>",
"content_en" : "<p>Easy (and free!) You should check out our premium features.</p>",
"slug_nl" : "Subpage",
"slug_en" : "Subpage",
"name_nl" : "Subpage1",
"name_en" : "Subpage1",
"date" : ISODate("2016-12-21T14:58:54.819Z"),
"subPages" : [],
"is_footerMenu" : 0,
"is_headMenu" : 0,
"visible" : 1,
"_id" : ObjectId("585a98ae6f657b52489087a9")
}
]
}
I want to remove subobject with ID
585a98a46f657b52489087a8
How can I do it?
Mongoose | deleteOne() Function The deleteOne() function is used to delete the first document that matches the conditions from the collection. It behaves like the remove() function but deletes at most one document regardless of the single option.
In Mongoose, subdocuments are documents that are nested in other documents. You can spot a subdocument when a schema is nested in another schema. Note: MongoDB calls subdocuments embedded documents.
In order to remove an element (subdocument) from an array you need to $pull it.
Page.update({
'subPages._id': req.body.ID
}, {
$pull: { subPages: { _id: req.body.ID } }
}, function (error, result) {
console.log(result);
});
If you want to remove all subdocuments (i.e. make the subPages
to be empty), you can $set its value to be an empty array.
Page.update({
'subPages._id': req.body.ID
}, {
$set: { subPages: [] }
}, function (error, result) {
console.log(result);
});
Hope it helps.
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