Update validation with a value

Hello there, I am using mongodb for a seat booking application.
What is the best way to make sure more than 1 do not book a seat.

Can I do a validation with a value on update to mark a seat booked?

thanks
Srikanth

Hi @SrikantH,

Welcome to MongoDB community.

I think that the best way is to use a findAndModify operation when a user clicks a seat for booking.

db.seats.findAndModify({ seatId: ..., status: "free" },{$set : {status : "booking"}});

Once the seat is booked you can user booking details to user data. And maybe place the userid on the seat document as booked .

If the user clicks a seat that was just booked this query will return 0 and you can message that seat was booked and refresh seat map to user.

Thanks
Pavel

1 Like

To complete @Pavel_Duchovny’s response, you could also use Multi-Document Transactions. It depends how you have done your data model.

I wrote a blog post about it. In my example, Alice is trying to buy beers, but I have only 5 to sell… So I’m making sure I don’t have more beers in the shopping carts than I actually have in stock. So I don’t sell 6 beers by “accident”.

1 Like

Thank you Pavel, I did with update similarly… in the find part, I was checking for seat status to be “not booked” and only then booking…it was behaving as expected

findAndModify is deprecated, was asked to use findOneAndUpdate

thanks
Srikanth

2 Likes

Thankyou for posting this, learned a lot from this

1 Like