我的数据库中有一个conversations
集合,我正在使用Mongoose来更新单个文档的unread
标记。
这是我的代码:
router.post('/reply/:conversation_id', ensureAuthenticated, (req, res, next) => {
Conversation.findById(req.params.conversation_id, (err, conversation) => {
// If the user that's logged in was the one who created the conversation, and is submitting a reply, run this code
if (req.user._id == conversation.created_by_user_id) {
User.findById(conversation.sent_to_user_id, (err, user) => {
Message.create({
//...
}, (err, message) => {
if (err) {
console.log(err)
} else {
message.conversations.push(conversation._id)
conversation.unread = true
conversation.save() // This is being saved to the database
message.save()
res.redirect('/conversations/' + conversation._id)
}
})
})
} else {
// Otherwise, if the user that's logged in was *not* the one who created the conversation, and is submitting a reply, run this code
User.findById(conversation.created_by_user_id, (err, user) => {
Message.create({
//...
}, (err, message) => {
if (err) {
console.log(err)
} else {
message.conversations.push(conversation._id)
conversation.unread = true
conversation.save() // This is not being saved
message.save()
res.redirect('/conversations/' + conversation._id)
}
})
})
}
})
});
if
部分将conversation.unread = true
保存到数据库。 else
部分没有。
条件的两个部分基本上都做同样的事情(将对话的unread
标志保存为true
,并保存消息),但只有条件的第一部分才能设置{{1到真。
有人可以帮我弄清楚为什么unread
标记未在unread
声明中保存为true
吗?
答案 0 :(得分:0)
您正试图同步拨打save
。
.save
接受回调。它是异步的。
请参阅下面的我的版本。
router.post('/reply/:conversation_id', ensureAuthenticated, (req, res, next) => {
Conversation.findById(req.params.conversation_id, (err, conversation) => {
// If the user that's logged in was the one who created the conversation, and is submitting a reply, run this code
if (req.user._id == conversation.created_by_user_id) {
User.findById(conversation.sent_to_user_id, (err, user) => {
Message.create({
//...
}, (err, message) => {
if (err) {
console.log(err)
} else {
message.conversations.push(conversation._id)
conversation.unread = true
conversation.save() // This is being saved to the database
message.save()
res.redirect('/conversations/' + conversation._id)
}
})
})
} else {
// Otherwise, if the user that's logged in was *not* the one who created the conversation, and is submitting a reply, run this code
User.findById(conversation.created_by_user_id, (err, user) => {
Message.create({
//...
}, (err, message) => {
if (err) {
console.log(err)
//return here
return res.redirect('/error'); //
} else {
message.conversations.push(conversation._id)
conversation.unread = true
//.save takes a function callback
conversation.save((err) => {
//.save takes a function callback
message.save((err) => {
res.redirect('/conversations/' + conversation._id)
})
})
}
})
})
}
})
});