Reputation: 25
I'm trying to display a piechart using the Highchart package for Meteor. I've got it working with a static data source, like this:
series: [{
type: 'pie',
name: 'Sales',
data:
[
["Norway", 123123.32],
["Canada", 1977844.86],
["France", 2644017.71],
["Denmark", 28954612.34],
["United Kingdom", 3391712.21],
["United States", 9389789.51]
]
}]
in the series part of the .js of the template file.
But when I'm trying to use MongoDb's find statement it either shows no data or the report is showing up weirdly, I guess this is due to the formatting of the data resulted from the find query.
My data in the collection is looking something like this:
{ "_id" : "HsgEBrrSvBp6qzp8Q", "0" : "Norway", "1" : 9061000.58 }
{ "_id" : "5dvtddEogj6d5Zw7D", "0" : "Canada", "1" : 1977844.86 }
{ "_id" : "6XmfgjBG4dupes3ma", "0" : "France", "1" : 2644017.71 }
{ "_id" : "BB8Av8GRpPXPsWfzj", "0" : "Denmark", "1" : 2894312.34 }
{ "_id" : "44qbHdtA3wTtf9QFL", "0" : "United Kingdom", "1" : 3391712.21 }
{ "_id" : "YqyWGzXkT4pD532qJ", "0" : "United States", "1" : 9389789.51 }
I've also tried to only find the selected fields ("0" and "1")
SalesData.find({}, {_id:0}).fetch()
Anyone got any tips on how to get the data from a collection in a format that can be used in Highcharts?!
Thanks!
EDIT: I solved it by pushing the required values to an array and set that array as data source.
var seriesData = [];
var reportData = SalesData.find({});
reportData.forEach(function(countryData) {
var dataPoint = [countryData.Country, countryData.Total];
seriesData.push(dataPoint);
console.log(countryData.Country);
});
Upvotes: 1
Views: 1105
Reputation: 106
Actually you can convert the result from a find query directly into an array of values by using cursor.map.
Here is an example for your scenario (using ecmascript2015)
SalesData.find({}, {fields: {Country: 1, Total: 1}}).fetch().map((countryData) =>
{
{return [countryData.Country, countryData.Total]}
})
You should be able to get the data source format needed by highchart
Upvotes: 4
Reputation: 774
db result is a collection of objects (curly braces on each row). While the static data is an array of values (rectangular braces). So, you need to convert each row in db into array of values.
here is the mapping code:
var ds = [
{ "_id" : "HsgEBrrSvBp6qzp8Q", "0" : "Norway", "1" : 9061000.58 },
{ "_id" : "5dvtddEogj6d5Zw7D", "0" : "Canada", "1" : 1977844.86 },
{ "_id" : "6XmfgjBG4dupes3ma", "0" : "France", "1" : 2644017.71 },
{ "_id" : "BB8Av8GRpPXPsWfzj", "0" : "Denmark", "1" : 2894312.34 },
{ "_id" : "44qbHdtA3wTtf9QFL", "0" : "United Kingdom", "1" : 3391712.21 },
{ "_id" : "YqyWGzXkT4pD532qJ", "0" : "United States", "1" : 9389789.51 }
];
var asValueArray = ds.map(function(row){
return [row["0"],row["1"]];
});
Then, you just assign it to your series object:
series: [{
type: 'pie',
name: 'Sales',
data: asValueArray
}]
Upvotes: 1