Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate in mongoose without saving

Tags:

mongoose

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!") }
like image 690
Francisco Ryan Tolmasky I Avatar asked Feb 14 '15 19:02

Francisco Ryan Tolmasky I


People also ask

Does mongoose have built-in validation?

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.

What is validate in mongoose schema?

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.

What is mongoose unique validator?

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.

Is mongoose validation customizable?

Along with built-in validators, mongoose also provides the option of creating custom validations. Creating custom validations is also very simple.


1 Answers

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!') }       
});
like image 112
JohnnyHK Avatar answered Sep 30 '22 17:09

JohnnyHK