Model.validate()

Parameters
  • obj «Object»
  • pathsToValidate «Array»
  • [context] «Object»
  • [callback] «Function»
Returns:
  • «Promise,undefined»

Casts and validates the given object against this model’s schema, passing the given context to custom validators.

Example:

  1. const Model = mongoose.model('Test', Schema({
  2. name: { type: String, required: true },
  3. age: { type: Number, required: true }
  4. });
  5. try {
  6. await Model.validate({ name: null }, ['name'])
  7. } catch (err) {
  8. err instanceof mongoose.Error.ValidationError; // true
  9. Object.keys(err.errors); // ['name']
  10. }