Şahin Ersever
Şahin Ersever

Reputation: 356

Mongoose, update values in array inside an object in an array

How can i update values in array inside an object in an array.

{
    "_id" : ObjectId("63c7ca9584535c160ee4aaed"),
    "status" : "REJECTED",
    "steps" : [
        {
            "_id" : ObjectId("63c7ca9884535c160ee4ab03"),
            "status" : "REJECTED",
            "stepUsers" : [
                {
                    "_id" : ObjectId("63c7ca9884535c160ee4ab04"),
                    "status" : "REJECTED",
                }
            ]
        },
    ]
}

I tried to update using arrayFilters but that didn't work. Mongo throw an error MongoServerError: Found multiple array filters with the same top-level field name steps

                        Collection.updateOne({
                            _id: id
                        }, {
                            $set: {
                                "steps.$[steps].stepUsers.$[stepUsers].status": 'PENDING',
                            }
                        }, {
                            arrayFilters: [
                                { "steps._id": step._id },
                                { "steps.stepUsers._id": stepUser._id }
                            ]
                        })                   

I need to update steps.stepUsers.status in the collection.

Upvotes: 0

Views: 36

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

Try to change the arrayFilters: "steps.stepUsers._id" -> "stepUsers._id"

since arrayFilters is referencing the string inside the [], not the path to it.

Collection.updateOne({
  _id: id
},
{
  $set: {
    "steps.$[steps].stepUsers.$[stepUsers].status": "PENDING",
    
  }
},
{
  arrayFilters: [
    {
      "steps._id": step._id
    },
    {
      "stepUsers._id": stepUser._id
    }
  ]
})

See how it works on the playground example

Upvotes: 1

Related Questions