更新引用的集合后检索文档的最有效方法

时间:2019-02-28 14:59:00

标签: mongodb mongoose

我正在检索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" }));

1 个答案:

答案 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"
            });
        }
    });

引用:findOneAndUpdate