猫鼬回调地狱承诺

时间:2020-09-05 12:00:22

标签: javascript node.js mongoose promise es6-promise

由于模型之间的关系,我想将此回调切换为Promise,但遇到困难

router.post("/", middleware.isLoggedIn, (req, res) => {
  Campground.findById(req.params.id, (err, campground) => {
    if (err) {
      console.log(err);
      redirect("/campgrounds");
    } else {
      Comment.create(req.body.comment, (err, comment) => {
        if (err) {
          console.log(err);
        } else {
          comment.author.id = req.user._id;
          comment.author.username = req.user.username;
          comment.save();
          campground.comments.push(comment);
          campground.save();
          res.redirect("/campgrounds/" + campground._id);
          console.log("comment created");
        }
      });
    }
  });
});

试图尽我所能,但由于“无法读取null的属性'comments'”而导致错误

router.post("/", (req, res) => {
  const text = req.body.text;
  const newComment = new Comment({ text });
  Campground.findById(req.params.id)
    .then((foundCampground) => {
      newComment
        .save()
        .then((comment) => {
          comment.author.id = req.user._id;
          comment.author.username = req.user.username;
          comment.save();
          foundCampground.comments.push(comment);
          foundCampground.save();
        })
        .then(() => res.json("Comment added!"));
    })
    .catch((err) => {
      res.json(`Error ${err}`);
    });
});

TIA

2 个答案:

答案 0 :(得分:0)

您的数据库中似乎没有foundCampground的记录。在推送到数组之前,请始终进行测试以查看是否从数据库返回了一条记录。如果没有特定查询的记录,findById返回null

router.post("/", (req, res) => {
  const text = req.body.text;
  const newComment = new Comment({ text });
  Campground.findById(req.params.id)
    .then((foundCampground) => {
      newComment
        .save()
        .then((comment) => {
          comment.author.id = req.user._id;
          comment.author.username = req.user.username;
          comment.save();
          if(foundCampground !== null){ //Added these line
          foundCampground.comments.push(comment);
          }
          foundCampground.save();
        })
        .then(() => res.json("Comment added!"));
    })
    .catch((err) => {
      res.json(`Error ${err}`);
    });
});

答案 1 :(得分:0)

答案

用猫鼬查询不是保证。为了将查询更改为Promise,必须使用 .exec()函数。

示例

router.post("/", (req, res) => {
  const text = req.body.text;
  const newComment = new Comment({ text });
  Campground.findById(req.params.id)
    .exec() // This line makes the trick
    .then((foundCampground) => {
      newComment
        .save()
        .then((comment) => {
          comment.author.id = req.user._id;
          comment.author.username = req.user.username;
          comment.save();
          foundCampground.comments.push(comment);
          foundCampground.save();
        })
        .then(() => res.json("Comment added!"));
    })
    .catch((err) => {
      res.json(`Error ${err}`);
    });
});

参考

Mongoose: Queries are not promises