See the comments in this issue:
null is a valid value for a Date property, unless you specify required. Defaults only get set if the value is undefined, not if its falsy.
(it's about dates but it can be applied to numbers just as well.)
Your options are to either:
- add
required
to the field
- add a custom validator that would reject it
- use hooks/middleware to fix the issue
You might get away with a pre-save or post-validate (or some other) hook like this:
YourCollection.pre('save', function (next) {
if (this.port === null) {
this.port = undefined;
}
next();
});
but probably you'll have to use something like:
YourCollection.pre('save', function (next) {
if (this.port === null) {
this.port = 1234; // get it from the schema object instead of hardcoding
}
next();
});
See also this answer for some tricks on how to make null
trigger default values in function invocation:
This is unfortunate that Mongoose cannot be configured to tread null
as undefined
(with some "not-null" parameter or something like that) because it is sometimes the case that you work with data that you got in a request as JSON and it can sometimes convert undefined
to null:
> JSON.parse(JSON.stringify([ undefined ]));
[ null ]
or even add null
values where there was no (explicit) undefined
:
> JSON.parse(JSON.stringify([ 1,,2 ]));
[ 1, null, 2 ]