Skip to content

Instantly share code, notes, and snippets.

@r01010010
Last active August 29, 2015 14:11
Show Gist options
  • Save r01010010/2b4ca60d172295e09d48 to your computer and use it in GitHub Desktop.
Save r01010010/2b4ca60d172295e09d48 to your computer and use it in GitHub Desktop.
reusable validation function
/*** Dependencies ***/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
evPost = require(g.wizco.dirs.validators + '/post'),
UserSchema = require(g.wizco.dirs.models + '/user').Schema,
SuperSchema = require(g.wizco.dirs.models + '/SuperSchema');
/**
* Schema
* @type {Schema}
*/
var PostSchema = new SuperSchema({
title: { type: String, default: null, require: true },
ts_creation: { type: Date, default: Date.now() },
description: { type: String, default: null },
user: { type: UserSchema.tree}
}, evPost);
/**
* Exports
* @type {*|Model}
*/
module.exports = mongoose.model('Post', PostSchema);
/*** Dependencies ***/
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, ValidationError = require(g.wizco.dirs.libErrors + '/ValidationError');
/**
* SuperSchema
* Schema mongoose based SuperClass
*/
function SuperSchema(schema, _ev)
{
/**
* Inheritance from Schema constructor
*/
Schema.apply(this, [schema]);
this.ev = _ev;
var self = this;
this.methods.validate = function(cb){
self.ev.validate(self, function (err, result) {
if (err) return next(err);
if (result.hasError()) {
err = new ValidationError('Validation error', result);
}else{
err = undefined;
}
cb(err);
});
};
}
SuperSchema.prototype = Object.create(Schema.prototype);
SuperSchema.prototype.constructor = SuperSchema;
/**
* Validates document
* @param cb
* @returns {ValidationError}
*/
module.exports = SuperSchema;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment