I've been using MongoDB changeStreams with Node.js and socket.io;
I'm using a sort of pub-sub architecture, where for each subscription he's supposed to replace the previous changeStream with the new subscription.
The logic goes something like this:
- Client requests new subscription(it's related to a collection changeStream)
- If the client has a changeStream, the server closes such changeStream and replaces with the updated changeStream.
pseudoCode for subscription
// If it has a changeStream
if (socket.dbWatcher["users"]) {
// close changeStream
socket.dbWatcher["users"].removeAllListeners("change");
socket.dbWatcher["users"].close();
}
// Replace with new changeStream and pipeline
socket.dbWatcher["users"] = db.collection("users").watch(pipeline, {resumeAfter})
.on("change", (change) => {
socket.emit("users", change)
})
Things were getting slow so I checked the number of connections and it was way over the number of collections (16 collections vs 29 connections).
Once a socket disconnects, I close all changeStreams but the connctions are still there(database). I increased the poolSize, but having 29 connections is not normal.
This is the mongodb command that I use to check connections: db.serverStatus().connections