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

175
Views
Obtuve un resultado incorrecto cuando quiero actualizar el estado del usuario (en línea/fuera de línea) cuando el usuario se conecta o desconecta del servidor con socket io

lo malo es que el usuario actualizado en MongoDB no es el correcto, porque el usuario alterado es el último que se conecta o desconecta del servidor, aquí está el lado del servidor.

rutas/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!