Say I have a javascript object (the data
) and I want to check to see if it conforms to a given Schema
that I've defined.
Is there a way to do this without turning the schema into a model, creating an instance of that model populated with the data
, and running mymodel.validate()
?
I'd love to have a Schema(definition).validate(data, callback)
, but the validate
function is defined on the Document
class, from what I could tell.
Validation is an important part of the mongoose schema. Along with built-in validators, mongoose also provides the option of creating custom validations. Creating custom validations is also very simple. Custom validations can be used where built-in validators do not fulfill the requirements.
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.
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.
Mongoose gives us a set of useful built-in validation rules such: Required validator checks if a property is not empty. Numbers have min and max validators. Strings have enum , match , minlength , and maxlength validators.
MongoDB uses a flexible schema model, which means that documents in a collection do not need to have the same fields or data types by default. Once you've established an application schema, you can use schema validation to ensure there are no unintended schema changes or improper data types.
To use Mongoose without defining a schema, we can define a field with the Mixed data type. to define the Any schema that has the any property set to the mixed type by setting the any property to {} or Schema.Types.Mixed. As a result, we can set any value as the value of any.
It is important to note that this example of validation in Mongoose is just that, validation in Mongoose. This has nothing to do with data validation at the database, or MongoDb level. Another thing to note is that this type of validation in Mongoose is complimentary to a validation package like Joi which we used in the node rest api tutorial.
A benefit of using Mongoose when inserting data into MongoDB is its built-in support for data schemas, and the automatic validation of data when it is persisted. You would not get this without Mongoose.
Mongoose added that functionality as Model.validate(...) back in 2019 (v5.8.0):
You can:
try {
await Model.validate({ name: 'Hafez', age: 26 });
} catch (err) {
err instanceof mongoose.Error.ValidationError; // true
}
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