1
messages: [
    {
        user: "5c57c85a9354fa24ad749137",
        text: "hello",
        unread: true
    },
    {
        user: "5c57c85a9354fa24ad749137",
        text: "world",
        unread: true
    }
]

I am trying to update all array elements where id does not match given id with the $[] but nothing happens

ChatSchema.update(
        {_id: mongoose.Types.ObjectId(req.body.conversationId), "messages": {$elemMatch: {"user": {$ne: mongoose.Types.ObjectId(req.body.userId)}}}},
        {$set: {"messages.$[].unread": false}},
        {multi: true}
        ).exec()

And when I use the single $ operator it only updates the first element found.

I am using mongo version 4.0.6 with mongoose version 6.7.0

I'm not human
  • 544
  • 1
  • 9
  • 30

1 Answers1

1

Matching criteria should be the $[identifier]

ChatSchema.update(
  { "_id": mongoose.Types.ObjectId(req.body.conversationId) }},
  { "$set": { "messages.$[msg].unread": false }},
  { "arrayFilters":[{ "msg.user": { "$ne": mongoose.Types.ObjectId(req.body.userId) }}] }
)
Ashh
  • 44,693
  • 14
  • 105
  • 132