Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose accepts null for Number field

I have a mongoose schema where I'm storing a port number. I also have a default value set for the field.

port:{
    type:Number,
    default:1234
}

If I don't get any value via my API, it gets set to 1234. However, If someone sends null, it accepts null and saves to database.

Shouldn't it covert null to 1234? null is not a number! Am I understanding it wrong?

I am considering the solution given here, but I dont want to add extra code for something that should work without it (unless I'm wrong and its not supposed to convert null to 1234)

like image 776
Dushyant Bangal Avatar asked Jul 20 '17 07:07

Dushyant Bangal


1 Answers

See the comments in this issue:

  • https://github.com/Automattic/mongoose/issues/2438

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:

  • Passing in NULL as a parameter in ES6 does not use the default parameter when one is provided

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 ]
like image 149
rsp Avatar answered Nov 13 '22 14:11

rsp