使用nodejs和moongose使用Chart.js绘制图形

时间:2016-10-23 20:30:22

标签: javascript node.js mongodb chart.js

我尝试使用Chart.js从mongodb绘制图表,代码App.js从mongodb读取数据并且工作正常。当我尝试将数据发送到client side以绘制图形时,会出现此问题。将数据发送到客户端以绘制图表的最佳方法是什么?在graph.ejs html文件下方绘制数据。

App.js

    var mongoose = require('mongoose');
    var Schema   = mongoose.Schema;
    ObjectID = require('mongodb').ObjectID;
    var configDB = require('./config/database.js');
    mongoose.connect(configDB.url);

    mongoose.model('Temperatura',
                   new Schema({ time: Number, temperature: Number}),
                   'col');

    var dados = mongoose.model('Temperatura');

            dados.find({}, function(err, data)
            {
                    if(err){
                            console.log(err, data, data.length);
                    }else{
                            console.log(data);
                    }

                    var Time = [];
                    var Temperature = [];
                    var Grafico = [];


                    for ( index in data){

                      var doc = data[index];
                      var objectId = new ObjectID(doc['_id'])
                      var time = objectId.getTimestamp();
                      console.log(doc['temp']);
                      var temperature = doc['temp'];

                      Temperature.push({"value" : temperature});
                      Time.push({"value" : time});

                      }
    }).sort('-date').limit(100);

app.get("/dados", function(req, res){
          res.render('grafico.ejs',{val: Temperature},{ message: req.flash('loginMessage') });
});

Graph.ejs

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <title>myWeather</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>
    <script type="text/javascript">
        var data = !{JSON.stringify(data)};
    </script>
</head>
<body>
    <% if (message.length > 0) { %>
        <div class="alert alert-danger"><%= message %></div>
    <% } %>
    <h1>Val: <span id="val"><%=val%></span></h1>
    <script>
        var data;
        getData(data);

        var x = data.x;
        var y = data.y;

        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: x,
            datasets: [{
                label: 'apples',
                data: y,
                backgroundColor: "rgba(153,255,51,0.4)"
          }]
        }
      });
    </script>
    <canvas id="myChart" syle="width: 80%; margin: 15px auto;"></canvas>

</body>
</html>

0 个答案:

没有答案