【发布时间】:2019-05-28 10:19:10
【问题描述】:
我是前端,我使用基于 Express + MongoDB 的 RBAC 做我的第一个 API。我需要对 await 函数获得的角色权限进行后处理。示例(此代码效果很好):
export async function getRoleById(req, res) {
try {
const role = await Role.findById(req.params.id)
.populate('permissions');
return res.status(HTTPStatus.OK).json(role);
} catch (err) {
return res.status(HTTPStatus.BAD_REQUEST).json(err);
}
}
结果:
{
"id": "5c27d6bfc51081331411dcd8",
"name": "writer2",
"permissions": [
{
"id": "5c27c43e2eb0c279ccd945ef",
"action": "create",
"subject": "task"
},
{
"id": "5c27c4532eb0c279ccd945f1",
"action": "read",
"subject": "task"
}
]
}
但我需要另一种格式的权限:
{
"id": "5c27d6bfc51081331411dcd8",
"name": "writer2",
"permissions": [
[ "create", "article" ],
[ "list", "user" ]
]
}
所以我尝试这样做:
export async function getRoleById(req, res) {
try {
const role = await Role.findById(req.params.id)
.populate('permissions')
.then((foundRole) => {
foundRole.permissions = foundRole.permissions.map(item => [ item.action, item.subject]);
return foundRole;
});
return res.status(HTTPStatus.OK).json(role);
} catch (err) {
return res.status(HTTPStatus.BAD_REQUEST).json(err);
}
}
用 exec 替换 then 并不会改变这种情况。执行此代码后,我有响应 200,但没有任何数据。空白页而不是带有角色数据的对象。
我阅读了很多关于 Mongoose 查询的文章,以及为什么使用带有回调的 async/await 是不正确的。在我的情况下,用 Promises 替换 async/await 是不可接受的方式。但是我应该怎么做才能得到我需要的结果呢?
【问题讨论】:
标签: node.js express mongoose async-await mongoose-populate