In mongoose.model, I have chosen the type of name
to be a string
and the type of age
to be a number
, but when I enter a number as the value of name, I don't get an error and the same thing happens when I use something like '18'
as the value of age.
Here is the code:
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
const me = new User({
name: 12,
age: '18'
});
me.save().then(() => console.log(me)).catch(error => console.log(error));
CodePudding user response:
Mongoose
casts the values to the corresponding type, if it fails a CastError
is thrown, from the doc:
Before running validators, Mongoose attempts to coerce values to the correct type. This process is called casting the document. If casting fails for a given path, the
error.errors
object will contain aCastError
object.
You can try this by given age
the value 'aa'
for example.
If you want to override this behavior you can use one of the following options:
- Disable casting globally:
mongoose.Number.cast(false)
- Disable casting just for a given path:
age: {
type: Number,
cast: false // Disable casting just for this path
},
- Use a custom function:
age: {
type: Number,
cast: v => { return typeof v === 'number' && !isNaN(v) ? Number(v) : v; } // Override casting just for this path
}