Skip to content

Instantly share code, notes, and snippets.

@zhenyanghua
Created October 4, 2016 19:04
Show Gist options
  • Save zhenyanghua/d24ea57cd70e69bcb82dc3bc8f14ea74 to your computer and use it in GitHub Desktop.
Save zhenyanghua/d24ea57cd70e69bcb82dc3bc8f14ea74 to your computer and use it in GitHub Desktop.
Loopback query role by user Id
var _ = require('underscore');
module.exports = function(Customer) {
Customer.getRolesById = function (id, cb) {
Customer.getApp(function (err, app) {
if (err) throw err;
var RoleMapping = app.models.RoleMapping;
var Role = app.models.Role;
RoleMapping.find({ where : { principalId: id }}, function (err, roleMappings) {
var roleIds = _.uniq(roleMappings
.map(function (roleMapping) {
return roleMapping.roleId;
}));
var conditions = roleIds.map(function (roleId) {
return { id: roleId };
});
Role.find({ where: { or: conditions}}, function (err, roles) {
if (err) throw err;
var roleNames = roles.map(function(role) {
return role.name;
});
cb(null, {"roles": roleNames});
});
});
});
};
Customer.remoteMethod('getRolesById', {
http: { path: '/getRolesById', verb: 'get' },
accepts: {arg: 'id', type: 'number'},
returns: { arg: 'payload', type: 'Object' }
});
}
@SpeedoPasanen
Copy link

When user has no roles, this returns all roles as then Role.find() will have no conditions. I recommend to add this to the beginning of the callback of RoleMapping.find():

if (!roleMappings.length) { return cb(null, { "roles": [] }); }

@xcyxiner
Copy link

xcyxiner commented Mar 7, 2018

if model base is RoleMapping , must add " strictObjectIDCoercion" in server/model-config.json, " RoleMapping.find({ where : { principalId: id }} " is not work.

strongloop/loopback#3121

Hello, I submitted strongloop/loopback-workspace#437 that will enable strictObjectIDCoercion for all new applications scaffolded using our lb/apic/slc tooling.

For existing applications, you can either add a boot script as @fabien shown above, or you can enable the setting via server/model-config.json:

{
  "RoleMapping": {
    "dataSource": "db",
    "options": {
      "strictObjectIDCoercion": true
    },
    "public": false
  }
}

As part of the update, according to #3198 (comment), you also need to update the data already stored in your MongoDB database to fix the type of the relevant id fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment