Forked from riodw/MongoDB-UserCollection-Data-Change_Send-Change-SocketIO.js
Created
November 11, 2019 18:36
-
-
Save ackuser/4da7740b1d5cad474317016d8fc0da32 to your computer and use it in GitHub Desktop.
Notify socket.io users when MongoDB data collection changes
This file contains hidden or 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