I found a way to solve this problem. This is not what I definitely want, but it works. First: join entity:
//Policy.js module.exports = { tableName: "users_roles", autoPK: false, attributes: { id: { type: 'integer', primaryKey: true, autoIncrement: true, }, user: { columnName: 'user_id', model: 'user' }, role: { columnName: 'role_id', model: 'role' } }, //tricky method to get all users for specified role_id //or to get all roles for specified user_id get: function(id, modificator, cb) { var fields = ['user', 'role']; if (fields.indexOf(modificator) < 0) { cb(new Error('No such modificator in Policy.get()'), null); } var inversedField = fields[(fields.indexOf(modificator) + 1) % 2]; var condition = {}; condition[inversedField] = id; this.find(condition).populate(modificator).exec(function(err, policies) { if (err) { cb(err, null); return; } var result = []; policies.forEach(function(policy) { result.push(policy[modificator]); }); cb(null, result); return; }); } }
As you can see, I added an identifier field to this object (and to db table users_roles too), so this is not a great solution.
//User.js module.exports = { tableName: 'users', autoPK: false, attributes: { id: { type: 'integer', primaryKey: true, autoIncrement: true, unique: true, }, name: { type: 'string' }, policies: { collection: 'policy', via: 'user' } } }
And the role:
//Role.js module.exports = { tableName: 'roles', autoPK: false, attributes: { id: { type: 'integer', primaryKey: true, autoIncrement: true, }, alias: { type: 'string', required: true, unique: true, }, policies: { collection: 'policy', via: 'role' } } }
The way I get all the roles for the specified user_id:
... id = req.session.me.id; //user_id here Policy.get(id, 'role', function(err, roles) { var isAdmin = false; roles.forEach(function(role) { isAdmin |= (role.id === 1); }); if (isAdmin) { next(null); return; } else { return res.redirect('/login'); } }); ...
Maybe it will be useful for someone =)