Setup Relationships & Validations

Alexey Gordeyev edited this page Dec 13, 2015 · 8 revisions

Back to Overview

Setup Relationships

User.hasMany(Post,   {as: 'posts',  foreignKey: 'userId'});
// creates instance methods:
// user.posts(conds)
// user.posts.build(data) // like new Post({userId: user.id});
// user.posts.create(data) // build and save

Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
// creates instance methods:
// post.author(callback) -- getter when called with function
// post.author() -- sync getter when called without params
// post.author(user) -- setter when called with object

// work with models:
var user = new User;
user.save(function (err) {
    var post = user.posts.build({title: 'Hello world'});
    post.save(console.log);
});

Setup Validations

User.validatesPresenceOf('name', 'email')
User.validatesLengthOf('password', {min: 5, message: {min: 'Password is too short'}});
User.validatesInclusionOf('gender', {in: ['male', 'female']});
User.validatesExclusionOf('domain', {in: ['www', 'billing', 'admin']});
User.validatesNumericalityOf('age', {int: true});
User.validatesUniquenessOf('email', {message: 'email is not unique'});

user.isValid(function (valid) {
    if (!valid) {
        return console.log(user.errors); // hash of errors {attr: [errmessage, errmessage, ...], attr: ...}
    }
});

Custom Validations

Recomended async.

Sync
function userNameValidator(err) {
     if (this.name === 'bad') { err(); }
});

User.validate('name', userNameValidator, {message: 'Bad name'});

var user = new User({name: 'Peter'});
user.isValid(); // true
user.name = 'bad';
user.isValid(); // false
Async
function userNameValidator(err, done) {
    process.nextTick(function () {
         if (this.name === 'bad') { err(); }
         done();
    });
});

User.validateAsync('name', userNameValidator, {message: 'Bad name'});

var user = new User({name: 'Peter'});

user.isValid(); // false (because async validation setup)
user.isValid(function (isValid) {
     isValid; // true
})
user.name = 'bad';
user.isValid(); // false
user.isValid(function (isValid) {
     isValid; // false
})