How to Use Mongoose Custom Validators

Introduction

Validating a schema is always recommended. Validations make the database better structured and avoid the insertion of bad data into it. Mongoose provides several built-in validators such as required, minlength, maxlength, min, and max. These built-in validators are very useful and simple to configure. But validations in mongoose are not limited only to built-in validators. We can also create custom validations. In this article, we will discuss how to create mongoose custom validators.

Defining schema without validations

We have a details collection and this is the schema defined for it.

let details = new Schema({
  name: {
    type: String
  },
  age: {
    type: Number
  },
  locations: {
    type: [String]
  }
});

Observe the third field, i.e. locations. Its type is the array of strings. As of now, there are no validations. This means, while inserting documents in this collection, we can skip any of these fields, or even we can skip all of them. Let’s try to insert an empty document using the mongo shell.

> db.details.insert({})
WriteResult({ "nInserted" : 1 })
>

Here we passed an empty object and it is inserted in the collection. But is this right? What is the point of this document? This is why we have validations to encounter such situations. We can use built-in validators but we will add a custom validator to the locations field.

Custom validators

As the type of locations field is the array of string. Currently, the array that is to be inserted can contain any number of items. Let’s create a validation here. Observe the locations field now.

let details = new Schema({
  name: {
    type: String
  },
  age: {
    type: Number
  },
  locations: {
    type: [String],
    validate: {
      validator: function(arr) {
        return arr.length > 2;
      },
      message: "You must provide more than 2 locations."
    }
  }
});

We added a new field, validate.

validate: {
            validator: function (arr) {
                return arr.length > 2
           },
           message: 'You must provide more than 2 locations.'
        }

We have to use the validate keyword to create custom validations. As its value, we will have an object that contains the validation.

validator: function (arr) {
                return arr.length > 2
           },

We defined a function as the validation that will check if the length of the array is greater than two or not. If the validation is violated, it will throw an error that contains a message that we specified in the next field.

message: 'You must provide more than 2 locations.'

So let’s check this using the postman tool.

Image from Gyazo

It throws an error indicating “You must provide more than 2 locations.” because we tried to insert two values.

Conclusion

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.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.