无法从loopback的Role模型中获取`role.id`

时间:2016-02-16 05:29:48

标签: javascript node.js loopbackjs

我正在after save

中的User模型上执行loopback.io方法

代码:
服务器/引导/ user.js的

module.exports = function(app) {
  var User = app.models.user;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;
  User.observe('after save', function setDefaultUserRole(ctx, next) {
    if (ctx.instance) {
      if (ctx.isNewInstance) {
        var userRole = ctx.instance.city != '' ? 'admin' : 'user';
        Role.find({name: userRole}, function(err, role) {
          if (err) {
            return console.log(err);
          }
          console.log(role);
          console.log(role.id);
          RoleMapping.create({
            principalType: RoleMapping.USER,
            principalId: ctx.instance.id,
            roleId: role.id
          }, function(err, roleMapping) {
            if (err) {
              return console.log(err);
            }
          });
        });
      }
    }
    next();
  });
};

在控制台中打印,

 [{ name: 'admin',
    created: Tue Feb 16 2016 10:57:27 GMT+0530 (India Standard Time),
    modified: Tue Feb 16 2016 10:57:27 GMT+0530 (India Standard Time),
    id: 56c2b33f624c3b680b86398b },
  { name: 'user',
    created: Tue Feb 16 2016 10:57:27 GMT+0530 (India Standard Time),
    modified: Tue Feb 16 2016 10:57:27 GMT+0530 (India Standard Time),
    id: 56c2b33f624c3b680b86398c }]
undefined

有人可以指导我如何从上面的代码段中检索role.id吗?

0 个答案:

没有答案