【发布时间】:2016-11-18 03:40:33
【问题描述】:
我已经设置了这样的架构。
它在创作上运行良好。如果缺少必需的或错误的类型,它将引发验证错误。所以它会检查类型和值(如果我添加额外的验证函数来验证每个字段上的值)
但是,当我尝试更新或 findOneAndUpdate 时。我已将 runValidators 设置为 true。它以某种方式工作,但它只会验证是否缺少任何必需的内容。但它没有验证类型,可能会自动将我的类型转换为格式。
例如,如果我将 isAction(预期为布尔值)设置为整数,它将自动转换为布尔值 false。所以它有点绕过类型验证。然后它将进入已经是布尔值的验证器函数,但我希望它应该在进入验证函数之前对类型抛出验证错误
另一个问题是数组和对象。它没有验证对象中的深层属性的类型,而是直接进入验证函数。
所以我想看看在更新/findOneAndUpdate 时是否有更好的方法来正确验证类型和值。
我已经搜索了一些 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);
});
【问题讨论】:
标签: node.js mongodb validation mongoose schema