How to convert `Promise` to `Array` in `Aggregation of rawCollection`?


#1

I try to use Aggregation of rawCollection like this

// Method
const data = Branches.rawCollection()
        .aggregate([
          {
            $match: { _id: '001' },
          },
          {
            $project: {
              _id: 1,
              name: 1,
              createdAt: 1,
              createdAtText: {
                $dateToString: { format: '%Y-%m-%d', date: '$createdAt' },
              },
            },
          },
        ])
        .toArray()

   // But can't forEach
   _.forEach(data, val => { ... })

#2

Here’s one way:

import { Promise } from 'meteor/promise';

const data = Promise.await(Branches.rawCollection()
        .aggregate([
          {
            $match: { _id: '001' },
          },
          {
            $project: {
              _id: 1,
              name: 1,
              createdAt: 1,
              createdAtText: {
                $dateToString: { format: '%Y-%m-%d', date: '$createdAt' },
              },
            },
          },
        ])
        .toArray());

#3

Excuse me Sir,
What difference Promise.await VS async/await???


#4

Basically, anything which is a Promise can be awaited, as long as it’s in an async function. So, another way of doing it would be:

Meteor.methods({
  async myMethod() {
    const data = await Branches.rawCollection()
      .aggregate([
        {
          $match: { _id: '001' },
        },
        {
          $project: {
            _id: 1,
            name: 1,
            createdAt: 1,
            createdAtText: {
              $dateToString: { format: '%Y-%m-%d', date: '$createdAt' },
            },
          },
        },
      ])
      .toArray();

      //...
  }
});

#5

Thanks again,
Could I use await multi times?

Meteor.methods({
  async myMethod() {
    const data = await Branches.rawCollection()
      .aggregate([
      ])
      .toArray();


    const data2 = await Branches.rawCollection()
      .aggregate([
      ])
      .toArray();

    const data3 = await Branches.rawCollection()
      .aggregate([
      ])
      .toArray();
      //...
  }
});

#6

Yes. As long as they’re inside an async function, they will just work.


#7

Thanks for your helping :blush: