使用mongoose从Mongo中删除子文档 [英] Remove sub-document from Mongo with mongoose
本文介绍了使用mongoose从Mongo中删除子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正试图从存储在猫鼬文档中的集合中删除一个项目.我的文档如下:
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": "5221040475f174d59a000005",
"items": [
{
"sku": 1321654654613213,
"name": "goldfish",
"quantity": 12,
"_id": "52224ed5bd9d340000000003"
},
{
"sku": 12,
"name": "goldfish",
"quantity": 13,
"_id": "52225dcbf2f1e40000000003"
},
{
"sku": 1299,
"name": "goldfish",
"quantity": 13,
"_id": "522260b6f2f1e40000000004"
}
]
}
我要删除sku为12的金鱼.我正在执行以下操作:
I want to remove the goldfish with the sku of 12. I am doing the following:
var inventory = res.locals.content;
inventory.items.remove( {sku: req.params.itemSku}, function (err, item) {
if (err) {
console.log('error occurred', err);
res.send('error');
}
else {
res.send('Item found and deleted');
return;
}
});
执行此操作时,出现错误"TypeError:无法读取未定义的属性'equals'".我不明白为什么.
when I do this, I get the error "TypeError: Cannot read property 'equals' of undefined". I don't understand why.
推荐答案
您需要inventory.items.pull(req.params.itemSku)
,然后调用inventory.save
. .remove
用于顶级文档
You want inventory.items.pull(req.params.itemSku)
, followed by an inventory.save
call. .remove
is for top-level documents
这篇关于使用mongoose从Mongo中删除子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文