Paulo Lima
Paulo Lima

Reputation: 178

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.

Upvotes: 2

Views: 3899

Answers (2)

Paulo Lima
Paulo Lima

Reputation: 178

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.

Upvotes: 1

sassy_rog
sassy_rog

Reputation: 1097

You can read into Mongodb or mongoose change streams which you can watch on change

Typical example from the mongoose website:

// Create a new mongoose model
const personSchema = new mongoose.Schema({
  name: String
});
const Person = mongoose.model('Person', personSchema, 'Person');

// Create a change stream. The 'change' event gets emitted when there's a
// change in the database
Person.watch().
  on('change', data => console.log(new Date(), data));

// Insert a doc, will trigger the change stream handler above
console.log(new Date(), 'Inserting doc');
await Person.create({ name: 'Axl Rose' });

you can read more on the mongoose or mongo website

Upvotes: 3

Related Questions