JS Object 尝试访问 Loopback 相关模型查询时的奇怪行为

JS Object strange behaviour when trying access Loopback related model query

我正在使用 Loopback Framework,做一个 Web 项目。 但我认为我在这里提出的问题与此关系不大,而是具有一般性的 Javascript / Node.JS 知识。

在代码的一部分,我正在做:

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);
            }
        }
});

好的,但是在尝试比较 roles[i].role.name 时失败了。 所以,我记录了 roles[i] object 包含的内容。

    { 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 } }

好的,没问题,但它仍然失败,所以我尝试只打印 role 属性。令我惊讶的是:

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

所以,role 属性 似乎是某种功能?但是之前是怎么正确打印出来的呢?

最终,在我的挫折中迷失了我尝试了var role = JSON.parse(JSON.stringify(roles[i]));

然后我可以正常访问 object 的每个 属性,但这既不干净也不正常。

这在我多年的 JS 编程中第一次让我震惊(虽然有点业余),如果有人能向我澄清这一点,我会很高兴。谢谢

编辑:它似乎是特定于此框架的,所以我正在更改标题以帮助社区。

我刚找到 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.

所以看来你必须使用

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