skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search