Before running the actual validation functions, mongoose will try to cast the model's value into their type declared in the schema.
If the cast operation is successful, then mongoose continues to the actual validation steps. As a result, it means that if one your value is a number that can be casted to a string, then the validation will succeed!
Most of the time it's probably fine, however if it's a problem for you, the set
function is a lot of help:
const schema = new mongoose.Schema({
mustBeAString: {
type: String,
required: true,
set: function (v) {
let validType = typeof v === "string" || v instanceof String;
if (validType) {
return v;
} else {
throw new Error("invalid type");
}
},
},
});
This way you can be sure that the value was a string from the start.
I have found this tip in this stackoverflow ticket, and then changed the code a little bit to actually throw an error.
Comments
Post a Comment