1

I'm currently stuck on getting all the users with certain role, for example admin users, in one angular SDK controller.

according to the docs of strongloop. what I did was:

User.find({
  filter: {
    include: [{'relation':'roles', 'scope': {
      where:{
        name:'admin',
      }}
    }],
  },
}, function(list) {
  console.log(list);
});

But the list i got is all the users, the non-admin users are included too. On the server side it is the default codes, i didn't change them.

{
  "name": "user",
  "plural": "Users",
  "base": "User",
  "properties": {

  },
  "relations": {
    "roles": {
      "type": "belongsTo",
      "model": "RoleMapping",
      "foreignKey": "principalId"
    }
  },
  "acls": [],
  "methods": []
}

Could you tell me what I made wrong? I don't want to loop through all the "list" from that query and filter the admin users, because it is a very huge list of users, but admin is for only 2 or 3 persons.

user1455180
  • 511
  • 4
  • 9

2 Answers2

2

Here is the solution of what i did, from the common/models/user.js, i created a remotemethod, called "getUsersByRole", and only accept "role", which is the name of the role:

User.remoteMethod('getUsersByRole', {
  accepts: [
    { arg: 'role', type: 'string', required: true },
  ],
  returns: {arg: 'users', type: 'string'},
  http: {
    verb: 'get',
    path: '/byrole/:role'
  }
});

then here is the function of it:

User.getUsersByRole = function(role, cb) {
    var loopback = require('loopback');
    var Role = loopback.getModel('Role');
    var userIdList = [];
    Role.findOne({include:'principals', where: {name:role}}, function(err, role) {
      role.principals(function(err, principals) {
        for (var i = 0; i < principals.length; i++) {
          userIdList.push(parseInt(principals[i].principalId));
        }
        if (userIdList.length > 0) {
          User.find({where: {id: {inq: userIdList}}}, function(err, users) {
            cb(err, users);
          });
        } else {
          cb(err, false);
        }
      });
    });
}

then run the lb-ng command to generate the service for angular client side, then run:

User.getUsersByRole({role:rolename}, function(list) {
});

in the controller.

user1455180
  • 511
  • 4
  • 9
0

Can you run the query from the role instead?

 Role.find({
      filter: {
        where: {name:'admin'},
        include: {'relation':'users'}            
      },
    }, function(list) {
      console.log(list);
    });
conradj
  • 2,481
  • 2
  • 24
  • 30