0

I am using the following Publication to aggregate active trials for my product:

    Meteor.publish('pruebasActivas', function() {
  var pruebasActivas = Clientes.aggregate([
    {
      $match: {
        'saldoPrueba': {
          '$gt': 0
        }
      }
    }, {
      $group: {
        _id: {
          id: '$_id',
          cliente: '$cliente'
        },
        totalPruebas: {
          $sum: '$saldoPrueba'
        }
      }
    }
  ]);
});

if (pruebasActivas && pruebasActivas.length > 0 && pruebasActivas[0]) {
  return this.added('aggregate3', 'dashboard.pruebasActivas', pruebasActivas);
}

Which throws the following object as a result

 {
  "0": {
    "_id": {
      "id": "YByiuMoJ3shBfTyYQ",
      "cliente": "Foo"
    },
    "totalPruebas": 30000
  },
  "1": {
    "_id": {
      "id": "6AHsPAHZhbP3fCBBE",
      "cliente": "Foo 2"
    },
    "totalPruebas": 20000
  },
  "_id": "dashboard.pruebasActivas"
}

Using Blaze how can I iterate over this Array with Objects in order to get "cliente" and "totalPruebas" to show?

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
Orozcorp
  • 176
  • 1
  • 11

1 Answers1

1

Make yourself a helper that converts the object into an array of objects, using only the top level keys that are not named _id:

Template.myTemplate.helpers({
  pruebasActivas: function(){
    var ob = myCollection.findOne(); // assuming your collection returns a single object
    var clientes = [];

    for (var p in ob){
      if (ob.hasOwnProperty(p) && p !== "_id"){

        // here we flatten the object down to two keys
        clientes.push({cliente: ob[p]._id.cliente, totalPruebas: ob[p].totalPruebas});
      }
    }
    return clientes;
  }
});

Now in blaze you can just do:

<template name="myTemplate">
  {{#each pruebasActivas}}
    Cliente: {{cliente}}
    Total Pruebas: {{totalPruebas}}
  {{/each}}
</template>

See iterate through object properties

Community
  • 1
  • 1
Michel Floyd
  • 18,793
  • 4
  • 24
  • 39