Skip to content

Instantly share code, notes, and snippets.

Last active August 16, 2020 03:34
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Drawing the MongoDB's data with Chart.js through WebSockets.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<div style="margin: 20px;display: block;">
<canvas style="width: 600px; height: 300px" id="chart"></canvas>
<script src=""></script>
var ws = new WebSocket('ws://');
var data = {};
ws.onmessage = function(response){
var responseData = JSON.parse(;
row.hour = new Date(row.hour).toISOString().slice(0, 16).replace('T',' ');
return row;
data[] = {};
data[][row.hour] = row.count;
var chart = new Chart(document.getElementById('chart').getContext('2d'));
var chartLine;
function drawChart(){
var palette = ['#CDA7C6','#7C7D9A','#8FBCCC'];
var chartData = {
labels: [],
datasets: []
for(var country in data){
var hours = data[country];
var counts = Object.keys(hours).map(function(x){return hours[x];});
var color = palette.pop();
var dataset = {
label: country,
data: counts,
pointColor: color,
strokeColor: color,
pointStrokeColor: '#fff',
fillColor: "transparent",
if(chartData.labels.length < Object.keys(hours).length){
chartData.labels = Object.keys(hours);
chartLine = chart.Line(chartData);
Copy link


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment