使用带有Node.Js的Chart.js中的动态数据

时间:2017-09-09 15:04:38

标签: node.js mongoose chart.js

路由器:

router.get('/:id', isLoggedIn, function (req, res) {
    Answer.findOne({ post: req.params.id }, function (error, answer) {
        Post.findOne({ _id: answer.post }, function (err, post) {
            res.render('post/stats', { title: post.ask });
        });
    });
});

图表功能:

var chart = new Chart($("#answerChart"), {
  type: 'pie',
  data: {
    datasets: [{
      label: "",
      backgroundColor: ["#3e95cd", "#8e5ea2"]
    }]
  },
  options: {
    title: {
      display: true,
      text: '{{ title }}'
    }
  }
});

chart.data.labels[0] = "Yes";
chart.data.labels[1] = "Test";
chart.data.datasets[0].data[0] = 5;
chart.data.datasets[0].data[1] = 3;

我需要从猫鼬动态检索数据,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以按如下所示在nodejs代码中进行字符串化

router.get('/doughnut', function(req, res) {
  data = [65, 59, 20, 81, 56, 55, 40, 62, 85, 76, 65, 81];
  console.log('doughnut data',data);
  res.render('dashboard/doughnut', {
    title:'My First Doughnut Chart', 
    datai: JSON.stringify(data)
  });
});

and in .pug template you parse it like
var idata = JSON.parse('!{datai}'); 

https://github.com/hiralyshah/chartjs_mongoose_mongoDB