findOneAndUpdate возвращает неопределенное - PullRequest
0 голосов
/ 16 февраля 2019

Когда этот маршрут выполнен, мое обещание возвращается неопределенным.Я знаю, что у меня есть правильный почтовый идентификатор, так как я проверил сам документ БД.Я не понимаю, почему, если он найдет документ, он даже вернет undefined.Заранее спасибо!

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);

1 Ответ

0 голосов
/ 16 февраля 2019

Ага, так что я .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" });
              });
          });
      }
    );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...