Question

I'm running the beta version(v0.10.0-rc3) of Sails.js with the updated database adapter(for PostgreSQL) so that I have the functionality of associations via the Waterline ORM. I am trying to create a role-based user model for authorization depending on different access levels. The User to Role association is a One-to-Many. My Models are:

api/models/User.js

module.exports = {

  attributes: {
    firstName: {
      type: 'string',
      required: true
    },
    lastName: {
      type: 'string',
      required: true
    },
    fullName: function() {
      return this.firstName + " " + this.lastName;
    },
    email: {
      type: 'email',
      required: true,
      unique: true
    },
    encryptedPassword: {
      type: 'string'
    }, 
    role: {
      model: 'role'
    },
    groups: {
      collection: 'group',
      via: 'users'
    }
  },  

  toJSON: function() {
    var obj = this.toObject();
    delete obj.password;
    delete obj.confirmation;
    delete obj._csrf;
    return obj;
  },

  beforeCreate: function (values, next) {
    // Makes sure the password and password confirmation match
    if (!values.password || values.password != values.confirmation) {
      return next({err: ['Password does not match password confirmation.']});
    }

    // Encrypts the password/confirmation to be stored in the db
    require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, encryptedPassword) {
      values.encryptedPassword = encryptedPassword;

       next();
    });
  }
};

api/models/Role.js

module.exports = {

  attributes: {
    name: {
      type: 'string',
      required: true,
      unique: true
    },
    users: {
      collection: 'user',
      via: 'role'
    },
    permissions: {
      collection: 'permission',
      via: 'roles',
      dominant: true
    }
  }
};

I know that Waterline doesn't support Through Associations yet, but I should still be able to access a role name that is associated with a user, correct? For example: user.role.name The only way I have been able to retrieve the role name as of now is to do a second query for the role object.

Was it helpful?

Solution

In order to access an associated model, you have to populate the association when you query the primary model, for example:

User.findOne(1).populate('role').exec(function(err, user) {

    if (err) {throw new Error(err);} 
    console.log(user.role.name);

}

Associations docs are here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top