MongoDB Collection as data source for cs.js in Meteor app

- QUESTION -

As the title says I'm using c3.js to plot charts in a Meteor app. All the examples, however, statically set the variables for the data source.
I can't find the correct way to use c3 with Mongo. Say I have a simple template like below
<template name="model1">
    <div class="chart"></div>
</template>
and then the chart code as follows
Template.model1.rendered = function () {
    var chart = c3.generate({
        bindto: this.find('.chart'),
        data: {
            json: [
                {name: 'www.site1.com', upload: 100
                    , download: 200, total: 400}
            ],
            keys: {
                value: ['upload', 'download']
            }
        },
        axis: {
            x: {
                // type: 'category'
            }
        }
    });
};
how can I populate that json field with the result of querying Mongo, something like Models.find({"model" : "model1"},{"actual" : 1, "_id": 0}).
Running the equivalent from the Mongo shell db.models.find({"model" : "model1"},{"actual" : 1, "_id": 0}) returns {"actual" : [ 1, 2, 3 ] }
I just can't figure out how to approach this

---------------------------------------------------------------------------------------------------------------

- ANSWER -

You can define Meteor.methods and Meteor.call to retrieve data and populate it into d3.
methods.js
Meteor.methods({

  data: function(){

    check(arguments, [Match.Any]);

    return Models.find({"model" : "model1"},{"actual" : 1, "_id": 0}).fetch();

  }

});
template.html
Template.model1.onRendered(function () {

  var self = this;

  Meteor.call('data', function (error, result) {

    var chart = c3.generate({
      bindto: self.find('.chart'),
      data: {
        json: result,
        keys: {
          value: ['upload', 'download']
        }
      },
      axis: {
        x: {
          // type: 'category'
        }
      }
    });

  });

});

0 comments:

Post a Comment

Powered by Blogger.