Marco Jr
Marco Jr

Reputation: 6806

MongoDB - Updating array inside an object

I've this simple json:

{
   id: 1,
   basket: {
        box: []
   }
}

I need to add itens inside the box array that's child of the basket array.

My attempt:

updateOne({ id: 1},  {
                "$push": {
                    "basket": {
                        "box": {
                            "dummy": "test"
                        }
                    }
                }
            }

but it's not working. I am receiving this exception:

UnhandledPromiseRejectionWarning: MongoError: The field 'basket' must be an array but is of type object in document

Upvotes: 0

Views: 48

Answers (1)

Jeremy M.
Jeremy M.

Reputation: 1164

You can access your object like so :

findOne({ id: 1}, 
{
  "$push": {
      "basket.box": {
        "dummy": "test"
      }
  }
}

Upvotes: 2

Related Questions