Mongoose布尔validation没有用,如果提供一个string

为了更容易validation我的input, 我试图确保只有在特定字段设置为true的情况下才能创buildmongoose文档 (这个字段当然总是如此,如果文档实际上是正确创build的,那就是为了报告原因)。

这是一个简化的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') }) 

问题是,即使我提供一个随机string而不是布尔值或“布尔string”(例如“false”或“true”而不是false / true),文档仍然正常保存,与标志设置为true。

如果我提供“假”或错误,validation工作正常,并引发错误。

显然,在validation(显然也是默认操作)实际上被调用之前,有一些types转换。 有没有办法让我来解决我的validation,或者我必须明确检查对象,然后才能创buildMongoose对象?

这是mongoose4.3.6。

你可以改变types布尔值为string和validation那样

  testField: { type : String, required: true, validate: { validator: function (value) { return value === "true" }, message: 'Field must be true' } }