【问题标题】:how to get data from mongodb and display as a d3 chart using nodejs如何从 mongodb 获取数据并使用 nodejs 显示为 d3 图表
【发布时间】:2015-10-05 10:58:07
【问题描述】:

我正在使用这个repo

这个 repo 提供了从 fixture_data.json 文件中的内部数据显示图表。

现在我想显示使用 mongodb 的数据。

然后我做一些改变

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');

这是我的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>

问题是:

当我尝试访问 http://localhost:3000/hello 时,页面会不断加载。

【问题讨论】:

    标签: javascript node.js mongodb express d3.js


    【解决方案1】:

    您需要正确初始化(调用 db.open 等)您的 Mongo 数据库连接。

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

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多