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' } }
- 在Node.js / Express.js中从数据库(MongoDB)caching数组
- 一个数据库,支持多区域应用
- MongoDB:select所有字段+子集合中所有匹配的元素
- 即使提供了文件,也可以在mongoose中获取validation错误
- 在20万条logging之后,Mongodb的回应令人难以置信
- 如何使用NodeJS以超级用户身份连接到另一个MongoDB数据库?
- 无法通过浏览器访问mongodb – 它看起来像试图通过本地驱动程序端口上的HTTP访问MongoDB
- 用Promise.all避免唯一的错误E11000
- 在amazon EC2上托pipenodeJS / mongoose web应用程序