【发布时间】:2018-08-29 09:31:16
【问题描述】:
我需要异步方法、MongoDB 和 Meteor 方面的帮助。 我尝试了 Generators、async/await、Promises,但没有解决我的问题。
我有一个函数,如果用户对某个角色有或没有权限,它会返回我。 此函数调用另一个函数来获取所有用户角色。所以我用聚合函数查询 Mongo 来恢复这个用户拥有的权限列表。
但我需要同步方式的 DB 的结果,就像 Meteor 使用其他方法一样。 我该怎么做?
class PermsServer {
has(role, companyIds = null, value = null){
const self = this;
const rolesData = self._getRoles(role, companyIds);
if (!rolesData[0]) return false;
// Check roles
const hasRole = self._checkType(rolesData[0], value);
return hasRole;
}
_getRoles(roles = null, companyIds = null){
const self = this;
const cursor = self.dataScope.aggregate([
{
$match: filter
},
{
$lookup: {
from: 'nx_perms',
localField: 'role',
foreignField: 'role',
as: 'perm_docs'
}
}
]);
return cursor.toArray(); // This returns a promisse 'Pending'
}
}
PS:我希望 _getRoles 结果是同步的
【问题讨论】:
-
如果它在服务器端,你试过docs.meteor.com/api/core.html#Meteor-wrapAsync 吗?
-
您调用的是本机 mongo 方法吗?因为在流星 mongo 集合中,您使用
fetch而toArray通常在本机 mongo 驱动程序中实现。 -
伊沃,是的,我试过了。我的代码实际上是这样做的:
const syncedAggregate = Meteor.wrapAsync(db.rawCollection().aggregate, db.rawCollection());const cursor = syncedAggregate(pipeline, options); -
@Jankapunkt Meteor 没有聚合,所以我需要使用 Mongo DB 的直接驱动和
rawCollection