Home > Software design >  DeleteOne by _id Mongodb
DeleteOne by _id Mongodb

Time:10-08

This is my first stack overflow question, and I'm excited to hear your thoughts.

> db.travelers.find().pretty()
{
        "_id" : ObjectId("615e3ddece93c870aca4e465"),
        "assembly" : [
                {
                        "_id" : ObjectId("615e3ddece93c870aca4e466"),
                        "SN" : 24,
                        "Model" : "J240",
                        "Job" : 1234,
                        "Revision" : "A",
                        "Version" : 1
                }
        ],
        "assyHistory" : [ ],
        "subAssemblies" : [
                {
                        "_id" : ObjectId("615e3deace93c870aca4e467"),
                        "SN" : 19,
                        "Model" : "P500"
                }

I am trying to delete the nested data in "subAssemblies" by its id. My current route:

router.delete("/subassembly/:id", deleteOneSubassembly);

my current controller:

  deleteOneSubassembly: async (req, res) => {
    try {
      const removeOne = await Traveler.deleteOne({
        _id: req.params.id
      });
      console.log(removeOne);
      res.json(removeOne);
    } catch (err) {
      res.send({ error: err });
    }
  }

And all I keep getting back is:

    "n": 0,
    "nModified": 0,
    "ok": 1

Wondering where I might be going wrong?

CodePudding user response:

use update and $pull the item

const removeOne = await Traveler.updateOne(
  {
     "subAssemblies._id": req.params.id
  },
  {
     "$pull": { subAssemblies: { _id:  req.params.id }
  }
});

aggregate

db.collection.update({
  "subAssemblies._id": ObjectId("615e3deace93c870aca4e467")
},
{
  $pull: {
    subAssemblies: {
      _id: ObjectId("615e3deace93c870aca4e467")
    }
  }
})

mongoplayground

  • Related