【发布时间】:2021-04-16 17:15:11
【问题描述】:
我有一个代码,我正在使用请求正文更新我的架构对象。我已经在架构上应用了验证规则。问题是,当请求正文中存在不存在的字段时,我希望架构抛出错误。不存在的键不会按我的意愿保存到数据库中,但我想抛出一些错误而不是保存对象。架构:
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));
}
});
【问题讨论】:
-
如果问题没有解决,请留言,如果解决接受我的回答,谢谢
-
@MohammadYaserAhmadi 好的,当我测试它时,我会继续。谢谢。
-
如果您的问题解决了,请接受我的回答
-
@MohammadYaserAhmadi,它没有用。但我照原样做。忽略多余的字段并保存记录。
标签: javascript node.js validation mongoose