Javascript 存在不存在密钥时出现Mongoose抛出错误
我有一个用请求体更新模式对象的代码。我已经在模式上应用了验证规则。问题是,当请求主体中存在不存在的字段时,我希望模式抛出一个错误。不存在的密钥不会按我的要求保存到数据库中,但我想抛出一些错误,而不是保存对象。模式:Javascript 存在不存在密钥时出现Mongoose抛出错误,javascript,node.js,validation,mongoose,Javascript,Node.js,Validation,Mongoose,我有一个用请求体更新模式对象的代码。我已经在模式上应用了验证规则。问题是,当请求主体中存在不存在的字段时,我希望模式抛出一个错误。不存在的密钥不会按我的要求保存到数据库中,但我想抛出一些错误,而不是保存对象。模式: const peopleSchema = new mongoose.Schema( { fullname: { type: String, required: [true, "fullname is r
const peopleSchema = new mongoose.Schema(
{
fullname: {
type: String,
required: [true, "fullname is required"],
validate: [(value) => isAlpha(value, "en-US", {ignore: " "}), "name should be alphabetic only"],
},
phone: {
type: String,
validate: [isPhone, "please enter a valid phone number"],
},
address: String,
},
{ timestamps: true }
);
更新人员的代码:
router.put("/:id", checkUser, async (req, res, next) => {
try {
const { id } = req.params;
const user = req.currentUser;
const person = user.people.id(id);
person.set(req.body);
const response = await user.save();
res.json({ response });
} catch (err) {
next(new BadRequestError(err));
}
});
对于验证,有两种方法基于
回调
和异步
方法,
因为您的代码是基于async/await的,所以必须像下面的代码一样使用validateSync()
:
let errors = user.validateSync()//check validation
if(errors){
console.log(errors)
throw errors;//handle your error
}
const response = await user.save()
在回调方法中:
user.save(function(err,response){
if (err){
console.log(err);
//handle error
}
else{
console.log(response)
res.json({ response });
}
})
如果问题没有解决,请留言,如果问题解决,请接受我的回答,谢谢you@MohammadYaserAhmadi好的,当我测试它时,我会继续。谢谢。如果你的问题解决了,接受我的建议answer@MohammadYaserAhmadi,它不起作用。但我现在就这么做了。只需忽略额外字段并保存记录。