dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 379 forks source link

Data types not validated #610

Open elad opened 9 years ago

elad commented 9 years ago

Hello,

Here's some code:

var orm = require('orm');

orm.connect('mongodb://localhost/dummy', function (err, db) {
  if (err) throw err;

    var Person = db.define('person', {
        name: String
    });

    var person = new Person({
        name: 1234
    });

    person.validate(function (err, errors) {
        if (err || errors) {
            throw new Error('validation failed');
        }

        person.save();
    });
});

I expected to see validate and save both fail, but that's not the case. After running this code, my MongoDB database has a new object with an Integer field for name with the value 1234.

Is this a bug? If not, is there a built-in way for enforcing types?

Thanks!

johanroyen commented 9 years ago

You need to manually add validators:

var Person = db.define('person', {
  name: String
}, {
  validations: {
    name: function (data, next, thisArg, contexts) {
      if (typeof data != 'string') {
        return next(new Error("%s is not a valid type for the field 'name'!", typeof data));
      }
      next();
    }
  } 
});