尝试访问回送相关模型查询时JS对象的奇怪行为 [英] JS Object strange behaviour when trying access Loopback related model query
问题描述
我正在使用Loopback Framework,正在执行一个Web项目. 但是我认为我在这里提出的问题与此无关,而是与Javascript/Node.JS的一般知识有关.
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);
}
}
});
可以,但是尝试比较roles[i].role.name
时失败.
因此,我记录了roles[i]
对象包含的内容.
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 } }
好,没错,但是仍然失败,因此我尝试仅打印role
属性.令我惊讶的是
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' }
那么,role
属性似乎是某种功能?但是以前如何正确打印呢?
So, the role
property seems to be some sort of function? But how it was been correctly printed before?
最终,由于挫败感,我尝试了var role = JSON.parse(JSON.stringify(roles[i]));
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.
这在JS编程年来是第一次让我大吃一惊(尽管有点业余),如果有人可以向我澄清这一点,我将感到很高兴.谢谢
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
似乎它特定于此框架,所以我要更改标题以帮助社区. p>
It seems that it is specific to this Framework, so I'm changing title to help community.
推荐答案
我刚刚发现 issue 1425 链接到以下文档:
I just found issue 1425 which links to the following docs:
使用Node.js API,您需要调用
toJSON()
将包含相关项的返回模型实例转换为普通的JSON对象
With Node.js API, you need to call
toJSON()
to convert the returned model instance with related items into a plain JSON object
请注意,关联属性[…]指向关联方法的JavaScript 函数.
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);
}
这篇关于尝试访问回送相关模型查询时JS对象的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!