【发布时间】:2016-04-24 19:27:46
【问题描述】:
为了更轻松地验证我的输入,我尝试确保只有在特定字段设置为 true 时才能创建 mongoose-document(此字段当然始终为 true,如果该文档实际上是正确创建的,这是出于报告原因)。
这是一个简化的 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')
})
问题是,即使我提供的是随机字符串而不是布尔值或“布尔字符串”(例如“false”或“true”而不仅仅是 false/true),文档仍然被正确保存, 标志设置为 true。
如果我提供“false”或 false,验证会正常工作并引发错误。
显然,在实际调用验证(显然还有默认操作)之前,存在某种类型转换。在创建 Mongoose-Object 之前,我有没有办法修复我的验证,或者我是否必须明确检查对象?
这是猫鼬 4.3.6。
【问题讨论】:
-
您找到解决方案了吗?在使用所有属性类型进行验证之前会发生相同的类型强制...
-
不,还没有。只有一种解决方法,我在将字符串传递给架构验证之前解析/验证字符串...
-
我也有两层验证。一种使用 mongoose 对数据库层上的数据库进行清理,另一种用于验证端点层上的输入。试图重用验证逻辑。不过不喜欢。仍然不确定我们是否真的需要两层验证。
标签: node.js mongodb validation mongoose