Mongoose: Decouple Schema Validation

Created on 29 Jun 2016  路  2Comments  路  Source: Automattic/mongoose

For utility purposes, it'd be quite nice if the Mongoose Schema Validator was a standalone module, and able to validate standalone JSON documents (for example, on the clientside).

enhancement

Most helpful comment

@martindale I have played around with this idea in my code a bit. I like the idea and agree that it would be nice to have validation separated from the other parts of mongoose, as this is a common issue in JS projects. The way I have done it is to use the standalone JSON as input to create a mongoose document and then call validateSync() on that.

var mongoose = require('mongoose');

var FooSchema = new mongoose.Schema({
  date: {type: Date},
  amount: {type: Number, min: 0, required: true}
});

var FooModel = mongoose.model('FooSchema', FooSchema);

var standalone = {
  date: new Date(),
  amount: 12345
};

var foo = new FooModel(standalone);

var errors = foo.validateSync();

if (errors) {
  throw errors;
}

All 2 comments

@martindale I have played around with this idea in my code a bit. I like the idea and agree that it would be nice to have validation separated from the other parts of mongoose, as this is a common issue in JS projects. The way I have done it is to use the standalone JSON as input to create a mongoose document and then call validateSync() on that.

var mongoose = require('mongoose');

var FooSchema = new mongoose.Schema({
  date: {type: Date},
  amount: {type: Number, min: 0, required: true}
});

var FooModel = mongoose.model('FooSchema', FooSchema);

var standalone = {
  date: new Date(),
  amount: 12345
};

var foo = new FooModel(standalone);

var errors = foo.validateSync();

if (errors) {
  throw errors;
}

Any chance this may be coming in the near future? It is awfully annoying to have to use separate validation logic for client side validations and data that does not need to go into the database

Was this page helpful?
0 / 5 - 0 ratings