0

So I have a model of Chat.

const Schema = mongoose.Schema;

const chatSchema = mongoose.Schema({
    id              : {type: String, required: true, unique: true},
    email1          : String,
    email2          : String,
    avasrc1         : String,
    avasrc2         : String,
    lastMessage     : String,
    lastMsgTime     : String,
    messages        : [{email: String, name: String, avasrc: String, msg: String, msgTime: String}]
});

And in server I want to change avatar sources to if email match email. So I tried...

await Chat.update({email1: email}, {$set: {avasrc1: avatar}}, {multi: true})
await Chat.update({email2: email}, {$set: {avasrc2: avatar}}, {multi: true})
await Chat.update({messages: {$elemMatch:{email: email}}},{"$set": {"messages.$.avasrc": avatar}}, {multi: true})

In a result it works only for first one. I need to change:

  1. All avasrc1 to avatar if email1 = email
  2. All avasrc2 to avatar if email2 = email
  3. All messages.avasrc in whole array to if messages.email = email

2 Answers2

0

No need to use multiple query for same collection. You can use one query like this,

await Chat.updateMany({email1: email}, {$set: {avasrc1: avatar, avasrc2: avatar}})

Check this documentation for further detail, update many mongo documentation

adeel
  • 321
  • 2
  • 8
  • I tried updateMany and it doesn't work. Also I don't want to change avasrc2 on email1 match, and avasrc1 on email2 match. – Aramazd Torosyan Dec 15 '20 at 06:06
  • Can you share collection data like 10 documents data? – adeel Dec 15 '20 at 06:43
  • This is a screenshot of chat example from MongoDB. https://ibb.co/frB2H5J I need change "avasrc1" if (email1: email) or change "avasrc2" if (email2: email) and change any "avasrc" in messages array where email: email – Aramazd Torosyan Dec 15 '20 at 09:47
0

I found an answer for my question by reading this answer for another question.

Final answer for this is.

await Chat.updateMany({email1: email}, {$set: {avasrc1: avatar}}, {multi: true})
await Chat.updateMany({email2: email}, {$set: {avasrc2: avatar}}, {multi: true})
await Chat.updateMany({"messages.email": email},{"$set": {"messages.$[elem].avasrc": avatar}}, { "arrayFilters": [{ "elem.email": email }], "multi": true })

Thanks for help, hope the answer will help someone else.