Gabriel Anderson
Gabriel Anderson

Reputation: 1391

Read synchronously data from Mongo with Meteor

I need a help with async methods, MongoDB and Meteor. I tried Generators, async/await, Promisses but nothing solves my problem.

I have a function that returns me if a user has or not a permission to a role. This function calls another one to get all user roles. So I query the Mongo with aggregate function to recover the list of permissions that this user has.

But I need the results of DB with synchronously way, like Meteor do with others methods. How I can do that?

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: I want the _getRoles result be sync

Upvotes: 0

Views: 675

Answers (1)

Gabriel Anderson
Gabriel Anderson

Reputation: 1391

Changes in MongoDB driver passes an AggregationCursor to the callback, whereas the 2.x version passed the aggregation result. Check issue #9936

For Meteor 1.7 we can use:

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

My other problem is that I debug a test with mocha, and I'm getting Timeout error. So I solve setting timeout to 0.

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

Upvotes: 3

Related Questions