【问题标题】:how to remove an object inside the array of objects in mongodb如何在mongodb的对象数组中删除一个对象
【发布时间】:2021-12-29 13:47:04
【问题描述】:

我想删除对象数组中的一个对象,我正在这样做

router.post("/delVendAttach", async (req, res) => {
  try {
    let vend = await Vendors.findOneAndUpdate({ "level1.email": req.body.email }, {
      $pull: {
        "level2.attachments": {
          _id: req.body.id
        }
      }
    })
    return res.status(200).send("Attachment Deleted Successfully");
  } catch (error) {
    console.log("error", error);
    return res.status(400).send(error);
  }
});

Here is the img of db collection

【问题讨论】:

  • 你的代码正确!,你能分享什么问题吗?..

标签: javascript node.js mongodb mongoose


【解决方案1】:

我认为您从level1.email 中找到并从level2 中删除该问题。 试试下面的代码可能对你有用!

let vend = await Vendors.findOneAndUpdate({ "level1.email": req.body.email }, {
  $pull: {
    "level1.attachments": {
      _id: req.body.id
    }
  }
})

【讨论】:

  • level2中没有附件
【解决方案2】:

【讨论】:

  • 无法显示相同的响应
  • 因此,如果您将ONE_OF_YOUR_COLLECTIONS 替换为Users,然后通过Id 过滤一个。你会得到一个User。我的用户看起来像Id(string), Tracks(Array of strings) 那么在$push mongo 方法Tracks 内部是我们要在用户内部使用req.body.Tracks 更新的数组,它是一个字符串数组。
  • 所以认为我们在 DB 中有一个看起来像 { Id:1, Elements:[1,2,3] } 的对象,我们通过它们的 ID 过滤到这个对象,在我们的例子中是 1 然后使用 $push 我们告诉 Mongo DB 替换我们的数组与输入之一。并且将upsert 设置为true,我们不替换它,我们将input array 包含到数据库中已经存在的数组中。如果我们的输入数组是[1,2,3,4,5],那么数据库会将我们对象的轨道数组更新为[1,2,3,4,5],如果我们想从这个简单的发送[1,2,3,4]中删除,那么数据库将有[1,2,3,4]
  • $push 可以,$pull 不行
猜你喜欢
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-16
相关资源
最近更新 更多