I am trying to remove an item from a collection that is stored in a mongoose document. My document looks like this:
{
\"__v\": 3,
\"_id\": \"5221040475f
You want inventory.items.pull(req.params.itemSku)
, followed by an inventory.save
call. .remove
is for top-level documents
const deleteitem = (req, res) => {
var id = req.body.id
var iditem = req.body.iditem
Venta.findOne({'_id': id}, function(err,result){
if (err) {
console.log(err);
}else{
result.items.pull(iditem)
result.save()
}
})}
module.exports = {deleteitem }
finaly!
MongoDB:
"imgs" : {"other" : [ {
"crop" : "../uploads/584251f58148e3150fa5c1a7/photo_2016-11-09_21-38-55.jpg",
"origin" : "../uploads/584251f58148e3150fa5c1a7/o-photo_2016-11-09_21-38-55.jpg",
"_id" : ObjectId("58433bdcf75adf27cb1e8608")
}
]
},
router.get('/obj/:id', function(req, res) {
var id = req.params.id;
Model.findOne({'imgs.other._id': id}, function (err, result) {
result.imgs.other.id(id).remove();
result.save();
});
The nicest and most complete solution I have found that both finds and removes a subdocument from an array is using Mongoose's $pull method:
Collection.findOneAndUpdate(
{ _id: yourCollectionId },
{ $pull: { subdocumentsArray: { _id: subdocumentId} } },
{ new: true },
function(err) {
if (err) { console.log(err) }
}
)
The {new: true}
ensures the updated version of the data is returned, rather than the old data.
Subdocuments now have a remove function. Use as follows from the spec:
var doc = parent.children.id(id).remove();
parent.save(function (err) {
if (err) return handleError(err);
console.log('the sub-doc was removed')
});
You can simply use $pull to remove a sub-document.
Collection.update({
_id: parentDocumentId
}, {
$pull: {
subDocument: {
_id: SubDocumentId
}
}
});
This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.