Reputation: 178
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
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:
socket.emit('UpdateOnDatabase');
io.on('connection', function(socket){
socket.on('UpdateOnDatabase', function(msg){
socket.broadcast.emit('RefreshPage');
});
});
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
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