【问题标题】:How to update a document field in mongoDB using mongoose findOneAndUpdate?如何使用 mongoose findOneAndUpdate 更新 mongoDB 中的文档字段?
【发布时间】:2021-01-14 18:09:31
【问题描述】:

我正在尝试通过 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.`
}

但是该字段没有被更新。

【问题讨论】:

  • 你的参数不匹配,应该是{ trainerID: req.body.trainerID }, { $set: { isVerified: true } }, { new: true } 第一个是查询/过滤第二个是你的更新部分,第三个是其他选项。
  • @turivishal 谢谢。这解决了我的问题。寒冷,尝试了一切期待这个:P

标签: node.js mongodb mongoose


【解决方案1】:

请输入以下代码:

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

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 2020-11-19
    • 2017-08-13
    • 2016-09-13
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2019-02-26
    相关资源
    最近更新 更多