Property of object in a nested array doesn't update when working with arrayFilters

In the database there is one document with an array history and inside that array 3 nested documents (objects) with a property “name” and a property “status”. 2 of these 3 documents (objects) have a value false for the status property.

This is the NodeJS code that is executed to update the document:

    Schema.invoiceModel.updateOne({id: req.params.id},
            // mogelijks gebeurt toch automatisch een insert!!!
            {
                $set:
                    {
                        "history.$[elem].status": true
                    }
            }
        , {
            arrayFilters: [
                {"elem.name": "voorschot betaald op"}
            ]
        }).then(result => {
        res.status(201).json(
        )
    }).catch(err => {
        console.log(err)
        res.status(500).json({
            error: err.errors
        })
    })

Why the document doesn’t update? The values of the status stays on false instead of becoming true…

Hello @Paul_Holsters,

The syntax of the code you had posted looks correct to me. It is difficult to tell what is the problem.

First, you can check if there is document in the collection with the query filter:
{ id: req.params.id }

Also, verify the value in the variable req.params.id.

I had tried some code verifying the syntax using an example, in the mongosh, and it works well:

// Sample document:
{
  id: 1,
  history: [
    { name: "alpha", status: false },
    { name: "beta", status: true },
    { name: "zeta", status: false }
  ]
}
// Update method
db.test.updateOne(
  { id: 1 }, 
  { $set: { "history.$[elem].status": true } },
  { arrayFilters: [ { "elem.name": "zeta" } ] }
)
1 Like