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?

2
  • 2
    use {{#each}}{{/each}} Commented Mar 12, 2016 at 15:59
  • This would return the object. There is only one document in the collection, and I have to display "Foo" or "Foo 2". Commented Mar 12, 2016 at 17:16

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.