Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

如何使用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/PATCHapi调用以验证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.`
}

但是该字段没有被更新。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

请输入以下代码:

//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.`
          })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...