How to update property of an object that is inside of an Array with mongoose

441 views Asked by At

So, I have a messageThread that has a reference to bunch of messages

var messageThreadSchema = new Schema({
    chatBetween: [{ type: Schema.Types.ObjectId, ref: 'User' }],
    messages: [{ type: Schema.Types.ObjectId, ref: 'Message' }],
    lastMessage: {type: String}
})

Accordingly, I have a message schema

var messageSchema = new Schema({
    sender: { type: Schema.Types.ObjectId, ref: 'User' },
    reciever: { type: Schema.Types.ObjectId, ref: 'User' },
    sentAt: { type: Date, default: Date.now },
    text: String,
    isRead: { type: Boolean, default: false }
})

I'm having a problem with updating message.isRead through messageThread.

I need to update isRead property of all messages that is inside messageThread


I've tried:

1.

 MessageThread.findByIdAndUpdate(req.body._id, {
  $set: {"messages.$.isRead": true} // I thought, maybe there is a typo and 
  "$set": {"messages.$.isRead": true} // tried too
  "$set": {"messages.$.isRead": "true"} // tried too
  })
  .populate({ path: "messages" })
  .exec((err, foundMessageThread) => {

});

2.

How to add update and delete object in Array Schema in Mongoose/MongoDB

MessageThread.update({'_id': req.body._id},
  {'$set': {
         "messages.$.isRead": true
   }},
      function(err,model) {
    if(err){
        console.log(err);
        return res.send(err);
    }
    return res.json(model);
});

3.

Then I decided to update isRead manually. I mean:

MessageThread.findById(req.body._id)
  .populate({ path: "messages" })
  .exec((err, foundMessageThread) => {
    var updatedMessage = foundMessageThread.messages.map(message=>{
        return {...message, isRead:true}
    })
    var newThread = {...foundMessageThread, 
    messages: [...foundMessageThread.messages, ...updatedMessage]}
    newThread.save()
  });

Of course it doesn't work in Node. So I had to redo everything using Object.assign() which made my code more messy.((

My question:

  1. Why my 1 and 2 methods are not working?
  2. Is there any easier method?
0

There are 0 answers