简体   繁体   中英

how to get data from mongodb and display as a d3 chart using nodejs

I am using this repo .

this repo provide displaying the chart from internal data which is in fixture_data.json file.

now I want to display the data from using mongodb .

then i do some changes

app.js

var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient,
    mongodb = require('mongodb'),
    Server = require('mongodb').Server;

app.engine('.html', require('ejs').__express);
app.set('views', __dirname);
app.set('view engine', 'html');

var mongoclient = new MongoClient(new Server("localhost", 27017));
var db = mongoclient.db('mydb');

var fixtureData = require('./fixture_data.json');
app.locals.barChartHelper = require('./bar_chart_helper');


app.get('/', function(req, res) {

  res.render('index', { fixtureData: fixtureData });
});

app.get('/hello', function(req, res) {
    db.collection('things').find({},{'Created':1, 'Total Price':1}).toArray(function(err, doc){

      res.render('hello', { 'docs': docs});
    })

});


app.listen(3000);
console.log('listening on port 3000');

and this is my hello.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>D3 Server-side Demo</title>

    <style>
      body {
        background-color: #f5f5f5;
        font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
        font-size: 12px;
      }

      .svg-chart .background {
        shape-rendering: crispEdges;
        stroke: #ccc;
        fill: #fdfdfd;
        stroke-width: 1px;
      }

      .svg-chart .bar { fill: #4682B4; }
    </style>

  </head>
  <body>
    <h1>D3 Server-side Demo</h1>
   <%-
      barChartHelper.getBarChart({
        data: docs,
        width: 400,
        height: 300,
        xAxisLabel: '2012',
        yAxisLabel: 'Views',
        containerId: 'bar-chart-small'
      })
    %>
    <hr>
    <%-
      barChartHelper.getBarChart({
        data: docs,
        width: 800,
        height: 600,
        xAxisLabel: '2012',
        yAxisLabel: 'Views',
        containerId: 'bar-chart-large'
      })
    %> 
  </body>
</html>

the problem is :

when i try to access http://localhost:3000/hello then page is continuously loading .

You need to properly initialize (call db.open on, etc) your Mongo database connection.

docs: https://mongodb.github.io/node-mongodb-native/api-generated/db.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM