mongolate

A validation middleware for mongoose.

npm install mongolate
1 downloads in the last week
4 downloads in the last month

Mongolate

A validation middleware for mongoose.

Installation

npm install mongolate

Or you can clone the latest mongolate with git.

Quick Start

First, you should require the module.

var mongolate = require('mongolate');

Mongolate is aimed to be very easy to use. Supposing you have a schema called dogSchema, which has two field, name and age.

var dogSchema = new Schema({
  name: String,
  age: Number
});

And you want to ensure that the name of the dog cannot be longer than 12 characters. You can simply do this.

function validateName(name) {
  if(name.length > 12) {
    return 'Arent you tired of calling it?';
  };
  return null;
};

mongolate(dogSchema, {
  name: validateName
});

The first argument of mongolate is the schema you want to add the validation to. And the second argument is an associated list whose key is a property of the schema and value the validation function. If you want to add an overall validation for the schema, that validation function will be the third argument. Note that either the second or the third argument is optional.

mongolate(schema, [validator_alist], [overall_validator]);

The argument passed to the validator functions in validator_alist is the property that it validates, these validators are called property validators.

The argument passed to the overall validator is the document itself. So you have to use the overall validator if the validation is associated with other properties or other models.

It cannot be easier to add an asynchronized validator. You only need:

function validateName(name, callback) {
  if(name.length > 12) {
    callback('Such a long name it has!');
  };
  callback(null);
};

mongolate(schema, {
  name: { validator: validateName, async: true }
});

Each validator should validate only one aspect. If you want to validate both the length of the name and the spelling of the name, you should use two validators, which is as easy as you see.

mongolate(dogSchema, {
  name: [validateLength, validateSpelling]
});

The validation stops as the first fails, and the overall validator is called until all the other validations are done.

Validation Error

Any validation failure causes an Error to be passed to the callback function, whose message attribute is 'Validation Error'.

If the validation for name fails, and the error message is 'Too long', then

dog.save(function(err) {
   err.message === 'Validation Error'; // True
   err.errors.name === 'Too long'; // True
});

Detailed Usage

1.Sorts of validators. There are two sorts of validators: property validators, and overall validators.

Property validators are used to validate one single property, and the argument passed to the validator is the property it validates.

Overall validators are used to validate the whole document, and the argument passed to the validator is the document itself.

function propertyValidator(prop) {
  //...
};

function overallValidator(document) {
  //...
};

mongolate(schema, { prop: propertyValidator }, overallValidator);

2.Return value of validators. For a synchronized validator, it returns null or undefined if the validation passes, or a string indicating the error.

For an asynchronized validator, it finishes the validation by calling the callback passed to it as the second argument.

// A synchronized validator.
function syncValidator(prop) {
  if(prop === 'Good') {
    return null;
  } else {
    return 'NotGood';
  };
};

// An asynchronized validator (Uniqueness validation).
function asyncValidator(prop, done) {
  myModel.findOne({ name: prop }, function(err, obj) {
    if (obj) done('Duplicated');
    else done();
  });
};
  1. Options of validators.

You can use a validator with default options by:

mongolate(schema, { prop: validatorFunc });

Or with specified options by: (taking async option as an example)

mongolate(schema, { prop: { validator: validatorFunc, async: true } });

Note that while you are specifying options for an overall validator, you have to put it in an array as if you are using more than one validators, to distinguish from the property validators which is also an object.

mongolate(schema, [ { validator: myOverall, async: true } ]);

Supported options:

  • async: true if the validator is asynchronized, false if the validator is synchronized. False by default.

  • Asynchronized versus synchronized validators.

An asynchronized validator need not return the validation result immediately. However, it calls the callback function to finish its validation. The callback function is the second argument. And it must call the callback, or the validation hangs up forever.

function asyncValidator(document, done) {
  // ...
  done(); // Validation passed.
  // Or
  done('Not a good value'); // Validation failed.
};
  1. More than one validators.

More than one validators should be put into an array, so are overall validators.

mongolate(schema, { 
    myprop: [ validator1, { validator: validator2, async: true } ] 
  }, 
  [ overall1, { validator: overall2, async: true } ]
);
npm loves you