Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda