node.js - 如何使用 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.`
}
但是该字段没有被更新。
解决方案
请输入以下代码:
//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.`
})
}
推荐阅读
- html - How can I maintain stacking divs on center meanwhile the second div take full remaining width
- javascript - 错误是:'TypeError:无法读取属性'uid''但它的定义
- android - 将 RefreshIndicator 与 FutureBuilder 一起使用(QuerySnapshot 问题)
- javascript - Select2 在模态框内未正确显示
- django - Google 应用引擎禁用请求日志记录
- javascript - 动态设置div的高度
- python - 如何在 docker 容器的 .net 核心应用程序中运行 python 脚本?
- python - 检查用户是否在完全不同的服务器中具有角色
- javascript - 如何防止倒数计时器将文本推到它旁边
- oracle - 如何通过将一行与其下一行进行比较来填充新列