How do I update a key in an array of objects in MongoDB?

Viewed 32

I working on NodeJS backend API and trying to change a key in an array of objects from false to true in my MongoDB database. I am passing two conditions from the client: the email of the user and the email of the person that sent the user a message. I would like to change the boolean value of read to true.

Sample data:

{
  _id: new ObjectId("6282163781acbcd969de3fc9"),
  firstName: 'Amanda',
  lastName: 'Nwadukwe',
  role: 'Volunteer',
  email: 'amandanwadukwe@gmail.com',
  password: '$2a$10$YD5MQlMt0gqSULQOBNcEfOLr3vIK8eF4dqdLw3XctsIVgbnf54P32',
  confirmPassword: '$2a$10$mnL0S1bDDkGVnKgqQP81mOew9aFdNTUCGOEs7LvWYRxzivN4hrtFS',
  date: 2022-05-16T09:14:57.000Z,
  messages: [
    {
      message: 'This is another message from Amanda',
      sendersEmail: 'laju@gmail.com',
      date: '2022-05-14T12:00:45.000Z',
      read: false
    },
    {
      sender: 'Amanda Nwadukwe',
      message: 'This is another message from Amanda',
      sendersEmail: 'amanda@gmail.com',
      date: '2022-05-14T12:00:45.000Z',
      read: false
    }]

Desired Output:

{
      _id: new ObjectId("6282163781acbcd969de3fc9"),
      firstName: 'Amanda',
      lastName: 'Nwadukwe',
      role: 'Volunteer',
      email: 'amandanwadukwe@gmail.com',
      password: '$2a$10$YD5MQlMt0gqSULQOBNcEfOLr3vIK8eF4dqdLw3XctsIVgbnf54P32',
      confirmPassword: '$2a$10$mnL0S1bDDkGVnKgqQP81mOew9aFdNTUCGOEs7LvWYRxzivN4hrtFS',
      date: 2022-05-16T09:14:57.000Z,
      messages: [
        {
          message: 'This is another message from Amanda',
          sendersEmail: 'laju@gmail.com',
          date: '2022-05-14T12:00:45.000Z',
          read: true
        },
        {
          sender: 'Amanda Nwadukwe',
          message: 'This is another message from Amanda',
          sendersEmail: 'amanda@gmail.com',
          date: '2022-05-14T12:00:45.000Z',
          read: false
        }]

I am tried a lot of things with filtering but I have not been successful. Here is my code to change all the read to true. It is also not working.

app.post("/view_message", (req, res) => {
  const email = req.body.email;
  
  Users.findOneAndUpdate({ "email": email }, {$set:{"messages.$.read": true}}, (err, result) => {
    console.log(result)
  })
});
2 Answers

You missed to add a check to match the array element to be updated.

Playground

db.collection.update({
  "email": "amandanwadukwe@gmail.com",
  "messages.sendersEmail": "laju@gmail.com", //This did the trick
  
},
{
  "$set": {
    "messages.$.read": true
  }
},
{
  "multi": false,
  "upsert": false
})

Just in case anyone needs it, to update all the read values for all objects in the array I used this:

User.findAndUpdateOne({
  "email": "amandanwadukwe@gmail.com",
  "messages.sendersEmail": "laju@gmail.com", 
  
},
{
  "$set": {
    "messages.$[].read": true //Added square brackets
  }
},
{
  "multi": false,
  "upsert": false
})
Related