Monday, 22 May 2017

Updating real time mongoDB data in nodejs

I am receiving "gData" in my html (chartjs is plotting it further), sent from this nodeJS code, but the problem is that, my data is real time and this code only sends it for once. I want to constantly push the data from here to my html or some other way? so that the charts stay most up to date. Logic that comes to my mind is that I should add a simple infinite loop from retrieving the data from database, pushing it then rendering it again and again, but will that be right? Given that the page will flicker again and again? The loop will terminate once the user moves to some other page while clicking any of the other tabs in my html that will force the other get requests I have to execute leaving this function. Thanks.

app.post('/', function(req, res) {
  MongoClient.connect('mongodb://user1:user1@hidden.mlab.com:hidden/sociology1', function (err, db) {
    if (err) throw err;
    console.log('Connected to DB');
    document={
      "_id": 1,
      "topic": req.body.tweet.topic,
      "time": req.body.tweet.time
    };
    db.collection('tweet_status').update({"_id": 1}, document, {upsert: true});
    db.collection('tweets_' + req.body.tweet.topic).find().toArray(function (err, data) {
      if (err) throw err
      console.log(data.length)
      res.render('twitter_graph',{gData:data});
    });
    res.render('twitter_graph');
    //res.send('Topic: ' + req.body.tweet.topic + 'Time: ' + req.body.tweet.time);
  });
});



via Titanz

No comments:

Post a Comment