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');
}
let 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);
let 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)
}
}
});
});