Last active
April 30, 2017 15:36
-
-
Save c0d0g3n/40b4b62041969abfafe4199c4101c047 to your computer and use it in GitHub Desktop.
Mongoose bug: SchemaType Boolean tries to convert input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mongoose = require("mongoose") | |
mongoose.connect("mongodb://localhost/bug") | |
let db = mongoose.connection | |
db.on('error', (err) => { | |
return console.error('Connection error:', err) | |
}) | |
testSchema = mongoose.Schema({ | |
test: { | |
type: String | |
}, | |
bool: { | |
type: Boolean | |
} | |
}) | |
let Test = mongoose.model('Test', testSchema) | |
new Test({ | |
test: 'bool true', | |
bool: true | |
}).save() | |
.then(() => { | |
return new Test({ | |
test: 'bool false', | |
bool: false | |
}).save() | |
}) | |
.then(() => { | |
return new Test({ | |
test: 'string string', | |
bool: "string" | |
}).save() | |
}) | |
.then(() => { | |
return new Test({ | |
test: 'array empty', | |
bool: [] | |
}).save() | |
}) | |
.then(() => { | |
return new Test({ | |
test: 'object empty', | |
bool: {} | |
}).save() | |
}) | |
.then(() => { | |
return Test.find() | |
}) | |
.then((tests) => { | |
// get results | |
console.log(tests) | |
// clean up db for next run | |
for (let test of tests) { | |
test.remove() | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "bug-report", | |
"version": "1.0.0", | |
"description": "", | |
"main": "bug.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"mongoose": "^4.9.6" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
testSchema = new mongoose.Schema({ | |
propertyThatAcceptsABoolean: { | |
type: mongoose.Schema.Types.Mixed, | |
validate: (input) => { | |
return input === true || input === false | |
} | |
} | |
}) | |
// We use schemaType mixed because it leaves the input untouched, | |
// then we define a custom validator that only resolves if the input is a (real) boolean. | |
// You can change the condition to also accept values like "true", "false", 0, 1... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment