首页 > 解决方案 > 如何使用 mongoose findOneAndUpdate 更新 mongoDB 中的文档字段?

问题描述

我正在尝试通过findOneAndUpdate猫鼬的方法更新 mongodb 文档中的字段。我在堆栈溢出中尝试过类似问题的几个答案。但我仍然面临这个问题。

这是我的模型架构

const auth = {
    trainerID: {
        type: String,
        required: true,
    },
    phone: {
        type: String,
        required: true,
    },
    otp: String,
    isVerified: Boolean,
    password: {
        type: String,
        required: true
    }
};

我正在POST/PATCH调用 api 来验证 OTP 并将该isVerified字段更新为 true,默认情况下该字段设置为false.

这是我的代码:

//Validate the otp
if (validTrainer.otp === req.body.otp ) {
        console.log(`send otp: ${req.body.otp}`);
        console.log(`original otp:${validTrainer.otp}`);
        await TrainerAuth.findOneAndUpdate({ trainerID: req.body.trainerID }, { new: true }, { $set: { isVerified: true } }, (err, newAuth) => {
            if (err) {
                console.log(err);
            } else {
                console.log(newAuth);
                res.send({
                    statusCode: 200,
                    message: `Phone number is verified.`
                })
            }
        })
    } else {
        res.send({
                    statusCode: 401,
                    message: `Wrong OTP. Try again.`
                })
    }
    

现在我得到了预期的回应

{
  statusCode: 200,
  message: `Phone number is verified.`
}

但是该字段没有被更新。

标签: node.jsmongodbmongoose

解决方案


请输入以下代码:

//Validate the otp
if (validTrainer.otp === req.body.otp ) {
  console.log(`send otp: ${req.body.otp}`);
  console.log(`original otp:${validTrainer.otp}`);
  await TrainerAuth.findOneAndUpdate({ trainerID: req.body.trainerID }, { isVerified: true }, { new: true }, (err, newAuth) => {
      if (err) {
          console.log(err);
      } else {
          console.log(newAuth);
          res.send({
              statusCode: 200,
              message: `Phone number is verified.`
          })
      }
  })
} else {
  res.send({
              statusCode: 401,
              message: `Wrong OTP. Try again.`
          })
}

推荐阅读