Forked from riodw/MongoDB-UserCollection-Data-Change_Send-Change-SocketIO.js
Created
July 16, 2019 03:14
-
-
Save zjhiphop/f0e1d3f00ccb82167dbf1f1837c24ace to your computer and use it in GitHub Desktop.
Notify socket.io users when MongoDB data collection changes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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