【问题标题】:findOneAndUpdate returns undefinedfindOneAndUpdate 返回未定义
【发布时间】:2019-07-10 13:26:42
【问题描述】:

当这条路线被执行时,我的承诺返回未定义。我知道我有正确的 Post id,因为我已经检查了 DB 文档本身。我不明白为什么如果它找到它甚至会返回未定义的文档。提前致谢!

router.post(
      "/comment/:id",
      passport.authenticate("jwt", { session: false }),
      (req, res) => {
        // Check Validation
        new Comment({
          user: req.user._id,
          text: req.body.text,
        })
          .save()
          .then(comment => {
            Post.findOneAndUpdate(
              { _id: req.params.id },
              { $push: { comments: comment._id } },
              { new: true }
            );
          })
          .then(post => {
            console.log(post);
            res.json(post);
          })
          .catch(err => {
            console.log(err);
            res.status(404).json({ postnotfound: "No post found" });
          });
      }
    );

发布架构

    const PostSchema = new Schema({
      user: {
        type: Schema.Types.ObjectId,
        ref: "users"
      },
      text: {
        type: String,
        required: true
      },
      likes: [
        {
          user: {
            type: Schema.Types.ObjectId,
            ref: "users"
          }
        }
      ],
      comments: [
        {
          type: Schema.Types.ObjectId,
          ref: "comment",
          date: {
            type: Date,
            default: Date.now
          }
        }
      ],
      date: {
        type: Date,
        default: Date.now
      }
    });

module.exports = Post = mongoose.model("post", PostSchema);

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    啊哈,所以我的 .then 与我的 Post.findOneAndUpdate 分离,这很有意义 =]

    router.post(
          "/comment/:id",
          passport.authenticate("jwt", { session: false }),
          (req, res) => {
            // Check Validation
            new Comment({
              user: req.user._id,
              text: req.body.text
            })
              .save()
              .then(comment => {
                Post.findOneAndUpdate(
                  { _id: req.params.id },
                  { $push: { comments: comment._id } },
                  { new: true }
                )
                  .then(post => {   <---
                    console.log(post);
                    res.json(post);
                  })
                  .catch(err => {
                    console.log(err);
                    res.status(404).json({ postnotfound: "No post found" });
                  });
              });
          }
        );
    

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 1970-01-01
      • 2021-01-29
      • 2019-10-14
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 2016-11-18
      • 2016-01-26
      相关资源
      最近更新 更多