[英]Given this model, how to delete a nested array item with updateOne (mongoose)?
[英]Unable to remove item from array using Mongoose / UpdateOne
我有一个 Node.js 应用程序,当 API 端点被命中时,我试图从数组中删除 object。 到目前为止,我无法让它更新/删除 object。 目前,以下查询返回没有错误,但在检查我的数据库时,我仍然看到它。 以下是我的查询和基本回复(我将添加更多内容,但不在此问题的 scope 范围内)。 我还包含了我的数据 model 的样本。 在下面的数据 model 中,我试图从 foo 数组中删除整个 object,因为它不再需要。 代码
const ID = req.params.id
await FooBar.updateOne({foo: {$elemMatch: {v_code: ID}}}, { $pull: {v_code: ID}}, (err) => {
if(err) return res.json({success: false, err})
return res.json({success: true, id: ID})
})
数据 model
{
bar: [
{
foo: [
{
v_code: <>
_id: <>
}
]
}
]
}
我确信在其他问题中已经提出了这个问题,但没有针对我的数据 model 的问题。 我尝试将多个 SO 帖子拼凑在一起,这就是我得到查询的 $elemmatch 和 $pull 部分的方式,到目前为止,我的运气为零
试试下面的命令:
db.collection.updateOne(
{
"bar.foo.v_code": ID
},
{
$pull: { bar: { foo: { $elemMatch: { v_code: ID } } } }
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.