【问题标题】:Read synchronously data from Mongo with Meteor使用 Meteor 从 Mongo 同步读取数据
【发布时间】: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 集合中,您使用 fetchtoArray 通常在本机 mongo 驱动程序中实现。
  • 伊沃,是的,我试过了。我的代码实际上是这样做的:const syncedAggregate = Meteor.wrapAsync(db.rawCollection().aggregate, db.rawCollection());const cursor = syncedAggregate(pipeline, options);
  • @Jankapunkt Meteor 没有聚合,所以我需要使用 Mongo DB 的直接驱动和rawCollection

标签: node.js mongodb meteor


【解决方案1】:

MongoDB 驱动程序中的更改将 AggregationCursor 传递给回调,而 2.x 版本传递了聚合结果。 检查问题#9936

对于 Meteor 1.7,我们可以使用:

import { Promise } from "meteor/promise";
const result = Promise.await(rawDonations.aggregate(pipeline).toArray());

我的另一个问题是我用 mocha 调试了一个测试,我得到了超时错误。 所以我解决了将超时设置为 0 的问题。

it('is SuperAdmin', function(){
    this.timeout(0);
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2015-11-17
    • 2014-12-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    相关资源
    最近更新 更多