-2

I am new to MEAN stack development. I have created a couple of charts using chartJS and i am able to give static values.

How can I get the values in the chart dynamically from MongoDB collections using Express.

I have separated front-end and back-end in two separate folders.

Chart Image

enter image description here

Praveen Kumar L
  • 61
  • 1
  • 10

1 Answers1

2

There are two ways to solve this problem: -

  1. Send data from your NodeJS backend while rendering the concerned HTML (with your Chart on it) --

    • So, setup a MongoDB Instance on mLab or Atlas. Then refer to any reference on how to use either MongoDB Client or Mongoose to connect to your MongoDB Database. Personally I recommend using Mongoose.
    • Next, in a route (let's say the home route), connect to your database and get the data you need for your chart. So, assuming you used express-generator, add something like this in your app.js

      mongoose.connect(<your-mongodb-connection-string-here>,function(err) 
      {
         if (err) {
            console.log(err);
         } else {
            console.log('Database ready to use.');
         }
      });
      
    • Then you'll need to add your database schema to a models folder, and export it so that you can access the db from your routes. Instructions here

    • And in your index.js put something along these lines: -

      var participant = require('../models/participants.js'); //Replace participant with the name of your created model
      
      router.get('/home', function(req, res, next) {
      
           participant.find({ username: 'starlord55' }, function(err, data) {
              if (err) throw err;
              //Write processing to extract the data that you need for your chart
      
              res.render('<name-of-your-view(ejs,jade)>',{chartData:data})
            });
      });
      
    • Now (assuming your view is ejs) the chartData object is accessible from your ejs file simply like this: -

      var data = [<%= chartData %>];
      

      Now, add this data to your chart while initialising the chart object.

  2. Using AJAX/Angular requests to fetch the data

    A lot of the same steps are involved, except that the data will not be sent at the res.render command. Instead, once the page is loaded, an AJAX request is used to request the data. Something like this. And once you get the data, add it to your chart in the same way.