【问题标题】:problem with koa, mongoose await not returning ctx.bodykoa 的问题,猫鼬等待不返回 ctx.body
【发布时间】:2020-05-16 10:21:05
【问题描述】:

我正在使用 koa 重置密码,想要使用 .save 来触发 schema.pre('save' )。

数据通过 findOneAndUpdate 返回,但在我使用 .save 时没有。

使用 await/asyncs 正确返回 .save 文档的神奇组合是什么?

r.post("/public/auth/resetpass", async (ctx, next) => {
  const values = ctx.request.body;
  const query = {
    email: values.email,
    resetPasswordToken: values.resetPasswordToken,
    resetPasswordExpires: {
      $gt: new Date(new Date())
    }
  };

  const update = {
    password: values.password,
    resetPasswordToken: null,
    resetPasswordExpires: null
  };

//  let userFound = null;

  await User.findOne(query,async function(err, user) {
    if (err) {
      console.log("*** err");
      next(err);
    } else {
      if (_.isEmpty(user)) {
        ctx.status = 200;
        ctx.body = {
          error: true,
          message: "token is incorrect or time has expired for password reset"
        };
      } else {
        user.password = values.password;
        await user.save(function(err, doc) {
          if (err) {
            console.log('***err saving');
            next(err);
          } else {
            //console.log fires, but ctx body doesn't return
            console.log ('***saved, writing poco');
            ctx.body = userToPoco(doc);
          }
        });
      }
    }
  });
});

【问题讨论】:

    标签: node.js mongoose koa


    【解决方案1】:

    最终转为承诺。

      await user.save().then (doc =>{
        ctx.body = doc;
      });
    

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 2020-10-16
      • 2016-06-22
      • 2019-05-10
      • 1970-01-01
      • 2022-12-18
      • 2018-08-30
      • 2019-03-20
      • 2018-07-24
      相关资源
      最近更新 更多