所以,我有一个 messageThread ,它引用了一堆邮件
var messageThreadSchema = new Schema({
chatBetween: [{ type: Schema.Types.ObjectId, ref: 'User' }],
messages: [{ type: Schema.Types.ObjectId, ref: 'Message' }],
lastMessage: {type: String}
})
因此,我有消息架构
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 }
})
我通过 messageThread 更新 message.isRead 时出现问题。
我需要 更新messageThread内所有邮件的 isRead 属性
我试过了:
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
然后我决定手动更新isRead。我的意思是:
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()
});
当然它在Node中不起作用。因此我不得不使用Object.assign()重做所有内容,这使我的代码更加混乱。((
我的问题: