簡體   English   中英

如何在 mongodb 的對象數組中刪除 object

[英]howto remove an object inside the array of objects in mongodb

嗨,我想刪除對象數組中的 object,我正在這樣做

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);
  }
});

這是db集合的img

我認為您從level1.email中找到並從level2中刪除該問題。 試試下面的代碼可能對你有用!

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

您可以使用以下代碼更新對象的數組數組

const collection = await getMongoDbCollection("ONE_OF_YOUR_COLLECTIONS")
// Filtering to the object that has the array of objects
let filter = {Id: req.params.id};

let options = {upsert: true};
// The following updates an array like add an element or delete one because of the upsert (even it is array of object or array of string)
let update =
    {
        $push: {
            Tracks: req.body.Tracks,
        }
    }

// Update your collection's entity by the `filter`  `update` and `options` variable
await collection.updateOne(filter, update, options);
res.status(200).send()

如果您有任何問題,請隨時發表評論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM