Search code examples
node.jsarraysmongodbmongoose

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.


Solution

  • 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