Mongoose accepts null for Number field

Viewed 7847

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)

2 Answers

As explained in mongoose official docs here

Number To declare a path as a number, you may use either the Number global constructor or the string 'Number'.

const schema1 = new Schema({ age: Number }); // age will be cast to a Number
const schema2 = new Schema({ age: 'Number' }); // Equivalent
const Car = mongoose.model('Car', schema2);
There are several types of values that will be successfully cast to a Number.
new Car({ age: '15' }).age; // 15 as a Number
new Car({ age: true }).age; // 1 as a Number
new Car({ age: false }).age; // 0 as a Number
new Car({ age: { valueOf: () => 83 } }).age; // 83 as a Number

If you pass an object with a valueOf() function that returns a Number, Mongoose will call it and assign the returned value to the path.

The values null and undefined are not cast.

NaN, strings that cast to NaN, arrays, and objects that don't have a valueOf() function will all result in a CastError.

Related