0

I am creating a chat with vue 3 and nodejs using mongoDb as database, i have the following structure in my model

{
  "_id": {
    "$oid": "63acbf00903200d01c44aecd"
  },
  "users": [
    {
      "$oid": "62e3df964db2354837e3461c"
    },
    {
      "$oid": "62e3df964db2354847e3463c"
    }
  ],
  "messages": [
    {
      "user": "62e3df964db2354847e3463c",
      "text": "Some text",
      "time": "December 28th 2022, 6:11 pm",
      "read": false
    },
    {
      "user": "62e3df964db2354847e3463c",
      "text": "Some text",
      "time": "December 28th 2022, 6:12 pm",
      "read": false
    },
    {
      "user": "62e3df964db2354847e3463c",
      "text": "Some text",
      "time": "December 28th 2022, 6:12 pm",
      "read": false
    },
    {
      "user": "62e3df964db2354847e3463c",
      "text": "Some text",
      "time": "December 28th 2022, 6:34 pm",
      "read": false
    },
    {
      "user": "62e3df964db2354837e3461c",
      "text": "Some text",
      "time": "December 28th 2022, 6:40 pm",
      "read": false
    }
  ],
}

I am grabbing the instance of the object and modifying it then saving it, but it does not work, how can I do this operation with a mongodb query?

this i what i got at the moment

export const saveReadMsgs = async (chatId,userId) => {
  try{
    const chatInstance = await chatModel.findById(chatId);
    if(chatInstance){
      chatInstance.messages.forEach(msg => {
        if(msg.read == false && msg.user != userId) msg.read = true;
      });
      await chatInstance.save();
    }
    console.log(chatInstance);
  }catch(e){
    console.error(e);
  }
}

should change the read property of each message object to true if the user is not the one who sent the message but the receiver.

1 Answers1

0

Assumption:

The parsed in userId is "62e3df964db2354847e3463c"

You can work with the update and arrayFilters to update the nested document within the messages array by condition.

let r = await chatModel.updateOne({
  _id: chatId
},
{
  $set: {
    "messages.$[message].read": true
  }
},
{
  arrayFilters: [
    {
      "message.user": {
        $ne: userId
      },
      "message.read": false
    }
  ]
})

Demo MongoDB Query @ Mongo Playground

To check whether is there any record is matched and modified, you can check the result with

console.log(r.matchedCount);
console.log(r.modifiedCount);
Yong Shun
  • 35,286
  • 4
  • 24
  • 46