【发布时间】: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