Dar*_*eye 6 javascript node.js loopbackjs
我正在使用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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
好的,但是在尝试比较时失败了roles[i].role.name.所以,我记录了roles[i]对象包含的内容.
{ 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 } }
Run Code Online (Sandbox Code Playgroud)
好吧,没有错,但它仍然失败,所以我试图打印role属性.令我惊讶的是:
{ [Function]
update: [Function],
destroy: [Function],
create: [Function],
build: [Function],
_targetClass: 'Role' }
Run Code Online (Sandbox Code Playgroud)
那么,该role属性似乎是某种功能?但之前是如何正确打印的呢?
最终,我试着失去了我的挫败感 var role = JSON.parse(JSON.stringify(roles[i]));
然后我可以正常访问对象的每个属性,但这不是干净也不正常.
这在多年的JS编程中首次引起了我的注意(尽管有点业余),如果有人能向我澄清这一点,我会很高兴.谢谢
编辑:它似乎特定于此框架,所以我正在改变标题以帮助社区.
使用Node.js API,您需要调用
toJSON()将返回的模型实例与相关项转换为普通的JSON对象请注意,关系属性[...]指向关系方法的JavaScript 函数.
所以看来你必须使用
for (var i=0; i<roles.length; i++) {
var x = roles[i].toJSON();
cb(null, x.role.name === 'teamLeader'
&& x.groupId === context.modelId);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1165 次 |
| 最近记录: |