'Mongoose - find object and delete objeto inside array

I have this document :

[
    {
        "_id": "626c5fd2aa0fc0e4eef45c94",
        "productos": [
            {
                "_id": "626d50b621180e291a330333",
                "nombre": "ciruelas",
                "descripcion": "marca lala",
                "codigo": 33,
                "foto": "https://cdn3.iconfinder.com/data/icons/fruits-52/150/icon_fruit_morango-256.png",
                "precio": 15,
                "stock": 30,
                "timestamp": "2022-04-30T15:06:45.128Z",
                "__v": 0
            }
        ],
        "timestamp": "2022-04-29T21:59:35.301Z",
        "__v": 0
    },
    {
        "_id": "626d508b21180e291a33032c",
        "productos": [],
        "timestamp": "2022-04-30T15:06:45.139Z",
        "__v": 0
    }
]

I would like to delete "ciruela" with "_id": "626d50b621180e291a330333" inside "productos".

How could i do that?



Solution 1:[1]

You could use $pull to remove the object with specified _id from the array productos

db.collection.update({
  "_id": "626c5fd2aa0fc0e4eef45c94"
},
{
  "$pull": {
    "productos": {
      "_id": "626d50b621180e291a330333"
    }
  }
})

Here is the link to the code for your reference https://mongoplayground.net/p/tsOJypb5Y6q

Solution 2:[2]

Solved!

I had to look for my "product" first.

async eraseMyProductFromCart (idProduct, idCart) {
        try{      
            const productSelected = await Product.findOne({_id:idProduct})
            await Cart.findByIdAndUpdate(idCart, {$pull: {"products": productSelected}})
            return Cart.find()                      
        }
        catch(error){
            console.log(error.message)
        }
    }

And then, pull that product when I do findByIdAndUpdate.

I donĀ“t know if that is the correct solution, but it worked for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JEFFRIN JACOB
Solution 2 Jeremy Caney