Skip to content

Commit

Permalink
Merge pull request #5344 from c0d0g3n/master
Browse files Browse the repository at this point in the history
`strictBool` option for schema type boolean (clean)
  • Loading branch information
vkarpov15 authored Nov 24, 2017
2 parents fe0d1c5 + aa6d05a commit 38131d4
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 9 deletions.
31 changes: 22 additions & 9 deletions lib/schema/boolean.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,29 @@ SchemaBoolean.prototype.cast = function(value) {
if (value === null) {
return value;
}
if (value === '0') {
return false;
}
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;

if (!this.options.strictBool) {
// legacy mode
if (value === '0') {
return false;
}
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
return !!value;
} else {
// strict mode (throws if value is not a boolean, instead of converting)
if (value === true || value === 'true' || value === 1 || value === '1') {
return true;
}
if (value === false || value === 'false' || value === 0 || value === '0') {
return false;
}
throw new CastError('boolean', value, this.path);
}
return !!value;
};

SchemaBoolean.$conditionalHandlers =
Expand Down
24 changes: 24 additions & 0 deletions test/schema.boolean.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,29 @@ describe('schematype', function() {
assert.strictEqual(true, m3.b);
done();
});
it('strictBool option (gh-5211)', function(done) {
var db = start(),
s1 = new Schema({b: {type: Boolean, strictBool: true}}),
M1 = db.model('StrictBoolTrue', s1);
db.close();

var strictValues = [true, false, 'true', 'false', 0, 1, '0', '1'];

var testsRemaining = strictValues.length;
strictValues.forEach(function (value) {
var doc = new M1;
doc.b = value;
doc.validate(function (error) {
if (error) {
// test fails as soon as one value fails
return done(error)
}
if (!--testsRemaining) {
return done()
}
});
});

});
});
});

0 comments on commit 38131d4

Please sign in to comment.