0

I want to track the number of connection a specific user makes using mongodb and node.js but I can't find the right way to do it

I have a database of users, each user has a document with a set limitation of how many pages open at the same time he can have but I can't track it. I tried using Socket.io but I couldn't find a way to assign different connections from different devices to the same account.

(I simplified the function, I don't actually save the code like this)

app.get('/', async (req, res) => {
    if (req.activationCode == '123') {
        return User.findOne({
            activationCode: '123'
        }, function (err, doc) {
            doc.active_users++;
            doc.save();
        }).then(docs => {
            res.render('index', {
                settings: docs.settings
            })
        })
    }
    res.render('login')
});

And I also have this code

io.on('connection', function (socket) {
    console.log('A user connected');

    socket.on('disconnect', function () {
        console.log('A user disconnected');
    });
});

Thanks a lot!

Mr Pickles
  • 75
  • 1
  • 4
  • Please explain how your code currently functions (i.e. what exactly isn't working). – jknotek Oct 04 '19 at 17:45
  • In this code I increase the number of active users every time a user access the page but I don't know how to know when to decrease this number... – Mr Pickles Oct 04 '19 at 18:49
  • You can track socket connection and disconnection on the server side, which will be the most reliable method. Take a look at this related question: https://stackoverflow.com/questions/17287330/socket-io-handling-disconnect-event – jknotek Oct 04 '19 at 19:21

0 Answers0