Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zjhiphop/f0e1d3f00ccb82167dbf1f1837c24ace to your computer and use it in GitHub Desktop.
Save zjhiphop/f0e1d3f00ccb82167dbf1f1837c24ace to your computer and use it in GitHub Desktop.
Notify socket.io users when MongoDB data collection changes
/* MongoDB-UserCollection-Data-Change_Send-Change-SocketIO.js */
'use strict'
module.exports = function (
app,
io,
User // Collection Name
) {
// SET WATCH ON COLLECTION
const changeStream = User.watch();
// Socket Connection
io.on('connection', function (socket) {
console.log('Connection!');
// USERS - Change
changeStream.on('change', function(change) {
console.log('COLLECTION CHANGED');
User.find({}, (err, data) => {
if (err) throw err;
if (data) {
// RESEND ALL USERS
socket.emit('users', data);
}
});
});
});
};
/* END - MongoDB-UserCollection-Data-Change_Send-Change-SocketIO.js */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment