Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
I got a wrong result when i want to update user status(online/offline) when the user connect or disconnect to the server with socket io

the wrong is that the updated user in MongoDB is not the right one, because the altered user is the last one connected or disconnected to the server , here is the server side.

routes/socket.js

      module.exports = function (io) {
      var array_of_connection = [];
      let senderTokent;
      const userIds = [];
    
      io.sockets.use(function (socket, next) {
        if (socket.handshake.query && socket.handshake.query.token) {
          jwt.verify(socket.handshake.query.token, "lol", function (err, decoded) {
            if (err) return next(new Error("Authentication error"));
            senderToken = decoded;
            next();
          });
        } else {
          next(new Error("Authentication error"));
        }
      }).on("connection", async function  (socket) {
        socket._id = senderToken.user._id;
        if (!userIds.includes(senderToken.user._id)) {
          userIds.push(senderToken.user._id);
          array_of_connection.push(socket);
        } else {
          console.log('user already opened socket');
        }
        
        const user = await db.userSchema.findOneAndUpdate({_id: senderToken.user._id}, {$set:{online: true}}, {new: true})
        for (let i = 0; i < array_of_connection.length ; i++) {
          if (array_of_connection[i]._id !== senderToken.user._id) {
           array_of_connection[i].emit('online-users', user._id);
          }
        }
       socket.on('disconnect', async () => {
      const userIndex = userIds.indexOf(senderToken.user._id);
      userIds.splice(userIndex, 1);
      const socketIndex = array_of_connection.indexOf(socket);
      array_of_connection.splice(socketIndex, 1);
        const user = await db.userSchema.findOneAndUpdate({_id: senderToken.user._id}, {$set:{online: false}}, {new: true})
        for (let i = 0; i < array_of_connection.length; i++) {
          if (array_of_connection[i]._id !== senderToken.user._id) {
            array_of_connection[i].emit('friend-leave2', senderToken.user._id)
          }
        }
  });
});
about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!