使用 mongoose 从 Mongo 中删除子文档 [英] Remove sub-document from Mongo with mongoose
本文介绍了使用 mongoose 从 Mongo 中删除子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从存储在 mongoose 文档中的集合中删除一个项目.我的文档是这样的:
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:无法读取未定义的属性‘等于’".我不明白为什么.
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屋!
查看全文