Problem: I wish to update multiple objects from my array schema. What I have tried is, this suggestion below, which I found here: Find and Update Object in Mongoose
Yes, this works, however, this will only update the first element on my messages_details array that holds the desired object.
await MessagesDetails
.update(
{
_id : message_id,
messages_details : {
$elemMatch : {
user_id: user_id
}
}
},
{
$set: {
'messages_details.$.message_isRead': true,
}
}
)
Here is my schema below:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const MessagesDetails = new Schema({
_id : Schema.Types.ObjectId,
messages_details_subject : {
type : String,
required : true
},
messages_details_sender : {
type : Array,
required : true
},
messages_details_recipient : {
type : Array,
required : true
},
messages_details_created : {
type : Date,
required : true
},
messages_details_updated : {
type : Date,
required : true
},
messages_details_isArchived : {
type : Boolean,
required : true
},
messages_details : [
{
user_id : Schema.Types.ObjectId,
user_username : {
type : String,
required : true
},
message_content : {
type : String
},
message_date : {
type : Date
},
message_isArchived : {
type : Boolean
},
message_isRead : {
type : Boolean
}
}
]
})
module.exports = mongoose.model( 'messages_details', MessagesDetails )
So my end goal here is, set the message_isRead to true based on these queries below;
_id
messages_details.user_id
Could someone please enlighten me?