I am designing an app that has many topics and for every topic there are some online users and for the same I am using express/socket.io/mongoose as backend and flutter as front end.
I am stuck at a part where I can show users that how many user is currently online for a topic in realtime(shown as list view in the frontend).
Topics are stored in the database.
So for I came up with this bit of logic but I think this is not the right way of doing it.
const roomChangeStream = roomModel.watch();
roomChangeStream.on('change', async (change) => {
topicModel.find().then((topics) => {
topics.forEach(topic => {
roomModel.find().where('isSearching').equals(true)
.where('preferredTopic').equals(topic.slug).count( (err,count)=>{
if (err) console.error(err);
console.log("the count for" +topic.slug+" is ",count)
// socket.emit
})
});
}).catch((err)=>console.log(err))
})
In the above code, I am looking for change in the room database (where online users are stored) and whenever there is a change I am looping through all the topics (100+) then search for online users count and emit them.
I know this is a bad piece of code. So I am looking for any help
Anyway, after a user connects to your server you save that client socket somewhere right? Mostly inside Redis or MemCached. To be more precise - the id of that socket. So, you can save additional data with it as well (topicId, userId). Then you can just count all sockets by filtering them with the topicId (as I understood you need active users per topic).