我已经设置了这样的架构 .
它在创作上运作良好 . 如果缺少必需或错误的类型,它将抛出验证错误 . 所以它会检查类型和值(如果我添加额外的验证函数来验证每个字段的值)
但是,当我尝试更新或findOneAndUpdate时 . 我已将runValidators设置为true . 它以某种方式工作,但它只会验证是否需要丢失 . 但它没有验证类型,可能会自动将我的类型转换为格式 .
例如,如果我将isAction(期望为布尔值)设置为整数,它将自动转换为布尔值false . 所以它绕过了类型验证 . 然后它将进入验证器函数,该函数已经是布尔值但我希望它在输入验证函数之前应该在类型上抛出验证错误
另一个问题是数组和对象 . 它没有验证对象中的深属性类型,而是直接进入validate函数 .
所以我想看看在更新/ findOneAndUpdate时是否有更好的方法来正确验证类型和值 .
我搜索了一些mongoose验证器模块,但大多数都是每个字段的验证函数的帮助器 . 所以这些数据已经从整数转换为布尔值,并且当时无法检查类型 .
此时,我只能想到在插入/更新到mongoose之前验证类型和值 .
const schema = new mongoose.Schema({{
id: {
type: String,
unique: true,
required: true,
},
address: {
formatted: String,
streetAddress: String,
locality: String,
region: String,
postalCode: String,
country: String,
},
isActive: Boolean,
});
const user = mongoose.model('User', schema);
// this one work with the validation on the type
User.create({ id : 'userA' }, (err) => {
console.log(err);
});
// fail to validate the type on both findOneAndUpdate
User.update({ id:'userA'},{ $set: { address:12313 }}, { runValidators: true}, (err) => {
console.log(err);
});
1 回答
本文https://www.mongodb.com/blog/post/introducing-version-40-mongoose-nodejs-odm详细讨论了猫鼬验证器 .
请查看 Pre and Post Hooks for Queries 部分,其中列出了用于count(),find(),findOne(),findOneAndUpdate()和update()的Mongoose 4功能前后挂钩 .
希望能帮助到你!!