Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda