我正在检索User
文档,并更新引用的评估的ObjectId并对其进行更新。现在,用户有了更新的参考,然后我再次搜索该用户以获取具有更新的User
参考的Assessment
文档。更新User
之后,有没有更有效的方法来拉起Assessment
文档?
router.post(
"/post",
passport.authenticate("jwt", { session: false }),
(req, res) => {
User.findOne({ _id: req.user._id }).then(user => {
Assessment.findOneAndUpdate(
{ _id: user.assessment._id },
{
$set: {
post: {
q1: {
question: req.body.q1.question,
answer: req.body.q1.answer
}
},
{
new: true
}
)
.then(assessment => {
User.findOne( <--- In question, trying to avoid querying the DB again
{ _id: req.user._id },
"name account_type corporation district email securityQuestions videos, assessment"
)
.lean()
.populate("assessment")
.then(user => res.json(user));
})
.catch(() => res.json({ Error: "Cannot update assessment" }));
答案 0 :(得分:1)
您已经通过设置Assessment.findOneAndUpdate
使{new: true}
返回了更新的文档,因此无需再次查询,并且已经获得了用户文档,只需将它们组合即可。
router.post(
"/post",
passport.authenticate("jwt", {
session: false
}),
async (req, res) => {
try {
let userDoc = await User.findOne({
_id: req.user._id
});
let assesmentDoc = await Assessment.findOneAndUpdate({
_id: userDoc.assessment._id
}, {
$set: {
post: {
q1: {
question: req.body.q1.question,
answer: req.body.q1.answer
}
}
}
}, {
new: true
});
userDoc.assesment = assesmentDoc;
res.json(userDoc);
} catch (error) {
res.json({
error: "Cannot update assessment"
});
}
});