我已经像这样设置了架构。
它在创作上效果很好。如果缺少必需的或错误的类型,它将引发验证错误。因此它将检查类型和值(如果我添加额外的验证函数来验证每个字段上的值)
但是,当我尝试更新或findOneAndUpdate时。我已将 runValidators 设置为 true。它以某种方式起作用,但它只会验证是否缺少任何必需的内容。但它没有验证类型,并且可能会自动将我的类型转换为格式。
例如,如果我将 isAction (期望为 bool 值)设置为整数,它将自动转换为 bool 值 false。所以它有点绕过类型验证。然后它将进入验证器函数,该函数已经是 bool 值,但我希望它应该在输入验证函数之前抛出类型验证错误
另一个问题是数组和对象。它没有验证对象中深层属性的类型,而是直接进入验证函数。
所以我想看看是否有更好的方法在 update/findOneAndUpdate 时正确验证类型和值。
我搜索了一些 Mongoose 验证器模块,但其中大多数都是每个字段的验证功能的帮助者。所以这些数据已经从整数转换为 bool 值,并且当时无法检查类型。
此时,我只能想到在插入/更新到 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);
});
最佳答案
这篇文章https://www.mongodb.com/blog/post/introducing-version-40-mongoose-nodejs-odm详细讨论 Mongoose 验证器。
请务必查看查询的 Pre 和 Post Hooks 部分,其中列出了 Mongoose 4 功能的 count()、find()、findOne()、findOneAndUpdate()、和更新()。
希望有帮助!!
关于node.js - Mongoose 如何在 update/findOneAndUpdate 时验证类型和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38387456/