You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Create a custom Schema.Type using Mongoose to check that the value is a valid email.
// function that calls a SchemaType with the given key and any optionsfunctionEmail(key,options){mongoose.SchemaTypes.String.call(this,key,options,'Email');}// link the prototype chains togetherEmail.prototype=Object.create(mongoose.Schema.prototype);// shadow the cast method from the linkageEmail.prototype.cast=(value)=>{constre=/^([A-Z|a-z|0-9](\.|_){0,1})+[A-Z|a-z|0-9]\@([A-Z|a-z|0-9])+((\.){0,1}[A-Z|a-z|0-9]){2}\.[a-z]{2,3}$/;if(!re.test(value)){returnmongoose.Schema.CastError('Email','A non-valid email was provided');}returnvalue;}// add to the Type registrymongoose.Schema.Types.Email=Email;// Then use like normalconstUser=Schema({email: Email,name: String});exportdefaultmongoose.model('User',User);
Alternative
Using a custom validate function which is found on the SchemaType prototype chain.
Usage
functionsomeFunction(value){constre= ... sameasabove;returnre.test(value);}constcustom=[somefunction,'Custom error message for file {PATH}, due to a passed in value of {VALUE}'];// could be used as the value of the validate keyconstUser=Schema({name: {type: String,validate: somefunction}// will return a SchemaType})
The someFunction could be an array of arguments to supply the validate function itself.
The error messages support basic templating. By passing in the array it looks to be unpacked and supllied to the function using validate.apply(null, custom) where custom is from the above snippet
Or instead of it directly in the Schema definition itself
I'm thinking a custom type here could be overkill given String types support match for regular expression validation. If anything we could abstract the location of regular expressions to a module to be reused anywhere else we'd need it, if you are leaning towards re-usability with the custom type.
Proposal
Create a custom
Schema.Type
using Mongoose to check that the value is a valid email.Alternative
Using a custom validate function which is found on the SchemaType prototype chain.
Usage
The
someFunction
could be an array of arguments to supply thevalidate
function itself.The error messages support basic templating. By passing in the array it looks to be unpacked and supllied to the function using
validate.apply(null, custom)
wherecustom
is from the above snippetOr instead of it directly in the Schema definition itself
Note for Validate
update()
orfindOneAndUpdate()
The text was updated successfully, but these errors were encountered: