Ben*_*wer 7 validation mongoose mongodb node.js
为了更容易验证我的输入,我试图确保只有特定字段设置为true才能创建mongoose文档(此字段当然总是正确的,如果文档实际上是正确创建的,则用于报告原因).
这是一个简化的poc:
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/playground')
var Schema = mongoose.Schema
var TestSchema = new Schema({
testField: {
type: Boolean,
required: true
}
})
// Try to ensure, that testField can only be true
TestSchema
.path('testField')
.validate(function (testField) {
return (testField === true || testField === 'true')
}, 'Test-field must be true!');
var Test = mongoose.model('test', TestSchema);
var newDoc = Test({
testField: 'some random string'
})
newDoc.save(function (err, newDoc) {
(err) ? console.log(err): console.log('newDoc was created')
})
Run Code Online (Sandbox Code Playgroud)
问题是,即使我提供的是随机字符串而不是布尔值或"布尔字符串"(例如"false"或"true"而不是false/true),文档仍然可以正确保存,标志设置为true.
如果我提供"false"或false,则验证工作正常并引发错误.
显然,在验证之前存在某种类型转换(显然也是默认动作).有没有办法让我修复我的验证,或者在创建Mongoose-Object之前是否必须明确检查对象?
这是猫鼬4.3.6.
这是一个接近黑客的解决方案,但它应该有效:
const mongoose = require('mongoose');
mongoose.Schema.Types.Boolean.convertToFalse = new Set([false]);
mongoose.Schema.Types.Boolean.convertToTrue = new Set([true]);
Run Code Online (Sandbox Code Playgroud)
请记住在第一个 require 之后立即设置这些,并密切关注缓存。
相关文档: https ://mongoosejs.com/docs/schematypes.html#booleans
即使有严格的模式,我们的 Mongoose 也会将五种不同的东西转换为 bool。真的磨我的齿轮。
| 归档时间: |
|
| 查看次数: |
1092 次 |
| 最近记录: |