I'm new in MongoDB Here is the thing I want to implement using mongoose and nodejs How to do a grouping of participants basics on room description.
//here is the schema
rooms.js
//ROOMS
const schema = mongoose.Schema({
"total_participants":{type: Number, default: 3},
"group_id": {type:String, default: ()=>utils.randomString(16)}
}
participants.js
//participants
const schema = mongoose.Schema({
---,
"group_id":String
});
API code, when someone joins the room, When someone tries to join first it gets groupId from the room and saves in participants and then it checks total no of joined participants in that room and if I got full than it generates a new id and updates in the room
const room= await RoomModel.findOne({_id: "5f2fde82b64b4e1c787ea611"})
await new ParticipantsModel({"group_id": room.group_id}).save()
const newGroupId= utils.randomString(16)
const filled =await ParticipantsModel.countDocuments({group_id: room.group_id})
console.log("filled "+filled)
await RoomModel.updateOne({total_participants:filled},{group_id: newGroupId}).exec()
The problem I'm facing here is when multiple user send at same time like 50 user send join request togher than the total participants in the room gets more in the room and new room Id not get updated .
It could be a concurrency issue; by the time you are inserting a new participant, the room is not marked as full yet and another one can get in.
In this case you need to use a transaction: https://mongoosejs.com/docs/transactions.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.