0

I am new with this and I am using Intellij as my editor for a project with nodejs, mongodb, express and jade/pug viewing engine. I need to view my data in a graph and decided to use chart.js. I can already access and view my data in a table but I want to show it in a graph.

Can someone help me understand how to include the chart.js file in the project. I have already npm installed it and it shows in my terminal, but how do I access this in the project. I have tried different things like including it as you do in a browser file or passing the exact directory link but maybe I am not understanding this. Please help!

Thanks!

Here are the files I have, most of it is default, I have made very minor edits only to fetch and display the data from a remote mongodb, where and how should I include the chartjs stuff. I tried the CDN method but I think I am not placing the link in the right place:

app.js is as:

    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');

    //New Code to connect remote Mongodb -Sg
    var mongo = require('mongodb');
    var monk = require('monk');
    var db = monk('username:passwd@ipaddress:27017/default', 
              {authSource:'admin'});

    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');

    var app = express();

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'pug');


    app.use(logger('dev'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

    // Make our db accessible to our router -Sg
    app.use(function(req,res,next){
         req.db = db;
         next();
    });


     app.use('/', indexRouter);
     app.use('/users', usersRouter);

     // catch 404 and forward to error handler
     app.use(function(req, res, next) {
       next(createError(404));
     });

    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });

    module.exports = app;

index.js is as:

    var express = require('express');
    var router = express.Router();

    /* GET home page. */
    router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });


/* GET envlist page. */
     router.get('/envlist', function(req, res) {
         var db = req.db;
         var collection = db.get('LORA_Sensor');
         collection.find({},{},function(e,docs){
            res.render('envlist', {
                 "envlist" : docs
            });
        });
     });

     module.exports = router;

envlist.pug file is as:

     extends layout

     block content


         h1
            Environment Parameter List

        ul
             p Co2
             each envparam, i in envlist

                li
                    p= envparam.Co2

new envlist.pug with just a graph using static data is below

    extends layout

    block content

        canvas#myChart
        script.
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
           type: 'line',
           data: {
              labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
              datasets: [{
                label: 'apples',
                data: [12, 19, 3, 17, 6, 3, 7],
                backgroundColor: "rgba(153,255,51,0.4)"
            }, {
                label: 'oranges',
                data: [2, 29, 5, 5, 2, 3, 10],
                backgroundColor: "rgba(255,153,0,0.4)"
            }]
        }
    });

layout.pug:

      doctype html
       html
        head
          title= title
          link(rel='stylesheet', href='/stylesheets/style.css')
          script(src='https://cdnjs.com/libraries/Chart.js')
        body

       block content
iris872
  • 11
  • 3
  • Try the CDN method instead to get started: https://www.chartjs.org/docs/latest/getting-started/installation.html – Graham Jan 09 '19 at 00:15
  • You might also want to add the code you've already tried in order to get assistance with a specific issue. – Graham Jan 09 '19 at 00:15
  • Thanks Graham, can you please look at the code and suggest how to import/use chart.js and where to place the import statement since I am using jade/pug as the viewing engine. – iris872 Jan 09 '19 at 07:49

1 Answers1

0

Try the CDN method by adding this to the layout.pug anywhere in the head section:

script(src='https://cdnjs.com/libraries/Chart.js')

Take a look at this question to see more details on how to reference chartjs as a local file from node_modules.

CDN is a lot easier to configure and will also be more economical as your server won't bear the load of serving the library to your users.

Graham
  • 7,431
  • 18
  • 59
  • 84
  • Hi Graham, I tried using CDN like you suggest (see original post for new edits in files), also I tried to render a graph with static data but it still does not render anything. Can you see if my new envlist.pug has the correct script format ? – iris872 Jan 10 '19 at 19:01