Search code examples
node.jsmongodbexpressexpress-handlebars

Refresh page automatically when MongoDB collection changes


I'm making a Node.Js with MongoDB application and I need to refresh one of my HBS pages every time something changes on my MongoDB collection.

Don't know exactly what I should do. What is the best approach to do so?

Cheers.


Solution

  • Thank you for all your help. The best (and easiest) solution that I've found was using websockets with Socket.io. I've used the following logic:

    • On my new user page I've added this on my submit event:
    socket.emit('UpdateOnDatabase');
    
    • On my app.js:
    io.on('connection', function(socket){
        socket.on('UpdateOnDatabase', function(msg){
            socket.broadcast.emit('RefreshPage');
        });
    });
    
    • And in my Home page, wich is the one that I want to refresh:
    var socket = io.connect('http://localhost:3000');
        socket.on('RefreshPage', function (data) {
            location.reload();
        });
    

    I've changed my way of thinking a bit but it's working exactly as I want.

    Cheers.