I'm working on my project, which is based on socket.io room. I used socket with nodejs and manage room data in mongoDB.
Here is my code, Only two players can join a room and then after I turn IsGameOn flag false to true.
This code is working fine when I send request to server one by one.
Problem occurs when many request comes at a time. And problem is more than 2 players join the room (Room players' data store in aPlayers Array).
I upload an Image of the database also. So, you can see what happen actually in the database.
const joinRoom = async (sData, callback) => { if(sData.iPlayerId && sData.eRoomCount) { try { let body = _.pick(sData, ['eRoomCount', 'iPlayerId']); console.log(body); await roomsModel.aggregate([ { $match: { eRoomCount: body.eRoomCount, IsGameOn: { $eq: false } } }, { $unwind: "$aPlayers" }, { $group: { _id: "$_id", eRoomCount: { $first: "$eRoomCount" }, aPlayers: { $push: "$aPlayers" }, size: { $sum: 1 } } }, { $match: { size: { '$lt': body.eRoomCount } } }, { $sort: { size: -1 } } ]).exec((error, data) => { if (data.length < 1) { let params = { eRoomCount: body.eRoomCount, aPlayers: [{ iPlayerId: body.iPlayerId }] } let newRoom = new roomsModel(params); console.log(JSON.stringify(newRoom)); newRoom.save().then((room) => { console.log("succ", room); callback(null,room); }).catch((e) => { callback(e,null); }); } else { roomsModel.findOne({ _id: data[0]._id }, (error, room) => { if (error) { callback(error,null); } if (!room) { console.log("No room found"); callback("No room found",null); } room.aPlayers.push({ iPlayerId: body.iPlayerId }); if (room.aPlayers.length === room.eRoomCount) { room.IsGameOn = true; } room.save().then((room) => { callback(null,room); }).catch((e) => { callback(e,null); }); }) } }); } catch (e) { console.log(`Error :: ${e}`); let err = `Error :: ${e}`; callback(e,null); } } } 
