#mongodb
Вопрос:
Я создаю чат-приложение. Если я нажму «Комната чата», я хочу изменить весь чат [{ …, читать: ложь => …, читать:истина }]
const userSchema = mongoose.Schema({
...
chats: [{
socketId: { type: String },
receiverId: { type: String },
receiverName: { type: String },
chat: [{
senderId: { type: String },
senderName: { type: String },
message: { type: String },
time: { type: String },
type: { type: String },
read: { type: Boolean }
}]
}]
})
Найдите чаты[] с req.user._id и receiverId
Я пробовал так, но это не работает
User.findOneAndUpdate({ _id: req.user._id, chats:{$elemMatch: {receiverId: req.body.receiverId }}},{
"$set" :{
"chats.$.chat": {
"read": true
}
}})
Комментарии:
1. Добавьте пример документа в вопрос вместо изображения. Также добавьте ожидаемый результат.
Ответ №1:
обновляет все read:false
до read:true
User.findOneAndUpdate(
{ _id: req.user._id },
{ $set: { "chats.$[elem].chat.$[].read" : true } },
{arrayFilters: [ { "elem.receiverId": req.body.receiverId } ],multi:true}
)