Is it possible to run the mongoose validator without also saving? Basically, wanting to do a dry run of a change and making sure that it would save if I chose to:
myThing.validated_property = 5;
try { myThing.check(); } catch(e) { console.log("nope!") }
Mongoose has several built-in validators. All SchemaTypes have the built-in required validator. The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator. Numbers have min and max validators.
Validation is defined in the Schema. Validation occurs when a document attempts to be saved, after defaults have been applied. Mongoose doesn't care about complex error message construction. Errors have type identifiers.
mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.
Along with built-in validators, mongoose also provides the option of creating custom validations. Creating custom validations is also very simple.
You can call validate
on a Mongoose doc to evaluate its validation rules:
myThing.validated_property = 5;
myThing.validate(function(err) {
if (err) { console.log('nope!') }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With