为了更容易地验证我的输入,我试图确保只有在特定字段设置为 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。
如果我提供"假"或假,验证工作正常并抛出错误。
显然,在实际调用验证(显然还有默认操作)之前,存在某种类型转换。有没有办法让我修复我的验证,或者我是否必须在创建猫鼬对象之前显式检查对象?
这是猫鼬 4.3.6。
这是一个接近黑客的解决方案,但它应该有效:
const mongoose = require('mongoose');
mongoose.Schema.Types.Boolean.convertToFalse = new Set([false]);
mongoose.Schema.Types.Boolean.convertToTrue = new Set([true]);
请记住在第一个要求之后立即设置这些,并密切关注缓存。
相关文档:https://mongoosejs.com/docs/schematypes.html#booleans
将我们的猫鼬投射五种不同的东西转换为布尔值,即使使用严格的模式也是如此。真的磨我的齿轮。
您可以将布尔类型更改为字符串并像这样进行验证
testField: {
type : String,
required: true,
validate: {
validator: function (value) {
return value === "true"
},
message: 'Field must be true'
}
}