Created
February 7, 2018 19:20
-
-
Save riodw/f1cdf875ee46e093e92ad917140eff95 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