JS Object strange behaviour when trying access Loopback related model query

给你一囗甜甜゛ 提交于 2019-12-01 03:51:36

问题


I am working with the Loopback Framework, doing a web project. But I think that the question that I am exposing here has less to do with this, but with general Javascript / Node.JS knowledge.

At one part of the code, I am doing:

roleMapping.find({
        where: {
            principalType: 'USER',
            principalId: context.principals[0].id
        },
        include: 'role'
    }, function(err, roles){
        console.log(roles[0]);
        for (var i in roles)
        {
            if (roles[i].role.name === 'teamLeader' &&
                roles[i].groupId === context.modelId)
            {
                cb(null,true);
            }else {
                cb(null,false);
            }
        }
});

Ok with this, but it fails when trying to compare roles[i].role.name. So, I went logging what the roles[i] object contained.

    { groupId: 1,
  id: 3,
  principalType: 'USER',
  principalId: 1,
  roleId: 2,
  role: 
   { id: 2,
     name: 'teamLeader',
     description: 'The leader(s) of a team',
     created: null,
     modified: null } }

Ok, nothing wrong, but it still fails, so I tried to print just the role property. And to my surprise:

{ [Function]
  update: [Function],
  destroy: [Function],
  create: [Function],
  build: [Function],
  _targetClass: 'Role' }

So, the role property seems to be some sort of function? But how it was been correctly printed before?

Eventually, lost in my frustration I tried var role = JSON.parse(JSON.stringify(roles[i]));

And then I could access every property of the object normally, but this is not clean nor normal.

This blew my mind for the first time in years of JS programming (sort of amateurish though), and I would be pleased if someone could clarify this to me. Thanks

EDIT: It seems that it is specific to this Framework, so I'm changing title to help community.


回答1:


I just found issue 1425 which links to the following docs:

With Node.js API, you need to call toJSON() to convert the returned model instance with related items into a plain JSON object

Please note the relation properties […] points to a JavaScript function for the relation method.

So it seems you have to use

for (var i=0; i<roles.length; i++) {
    var x = roles[i].toJSON();
    cb(null, x.role.name === 'teamLeader'
             && x.groupId === context.modelId);
}


来源:https://stackoverflow.com/questions/30927114/js-object-strange-behaviour-when-trying-access-loopback-related-model-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!