2👍
There are two ways to solve this problem: –
-
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.jsmongoose.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.
-
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.