Home > Blockchain >  how to remove an object inside the array of objects in mongodb
how to remove an object inside the array of objects in mongodb

Time:12-30

I want to remove an object inside the array of objects and I am doing this

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

CodePudding user response:

I think you find from level1.email and remove from level2 that the problem. Try below code may be works for you !

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

CodePudding user response:

Duplicate of Using $pull in Mongodb to remove a deeply embedded object

  • Related