Amr Ibrahim
Amr Ibrahim

Reputation: 2234

Mongoose custom validation function against race condition

We have a calendar API for booking a slot during a day

SlotShcema

startDateTime:Date  // showing the day and the starting hour
duration:number // showing the slot duration 

we can calculate the slot end

endDateTime = startDateTime + duration

We want add a validation, so no two slot intersect, and only one user can book it .

I found costume Async Custom Validators, but we cannot find any doc for our scenario .

The issue is to find way to solve the race condition where two concurrent saves might save conflicting bookings "transaction" . i did my own validate function before start create the slot, but if there is a race condition it may save two slots at same time which is wrong . Is there any way to solve the race condition ?

Issue on GitHub https://github.com/Automattic/mongoose/issues/5876

Upvotes: 2

Views: 164

Answers (1)

Amr Ibrahim
Amr Ibrahim

Reputation: 2234

Final work around worked for me is to call the function in queue with callback . it works for me, but it little slow .

This an example JS-Promise-Race-Condition-Queue


if you want to make this solution faster you should make queue per intersection which will make the concurrency conflict . for example date range .

You should follow the github issue link above to understand more about the situation .

Upvotes: 0

Related Questions