0

Following situation:

Users have balances:

user:{
 balance: 100
 id: xxx
}

Games have users and bet amount:

game: {
 bet: 1000,
 p1: yyy,
 p2: null
}

When a player joins a game, I need to check if his current balance is sufficient to match the games bet (set by the creator of the game: p1).

I could easily just do something like this:

const user = users.find({id: xxx})
const game = games.find({p2: null})

if(user.balance >= game.bet)
 games.updateOne({...}, {$set: {p2: user.id}})

BUT, this would only work if I only ever had one server instance running as otherwise I would run into a race condition between finding the game and deciding on the result.

MongoDB 4.0 comes with multi-document transactions however I cant seem to find a way to put them to use here. It seems like I need something else. I feel like what I need is a server side (db side) script in place that will run this logic on data whilst completely locking the users and games collection.

Am I right that you cant implement this without serverside scripts?

ThatBrianDude
  • 2,952
  • 3
  • 16
  • 42
  • This really is more than "kind of broad" in subject. The usual case is that we try to structure so all writes are in fact going to the same document, i.e a "balance" with an array of "amounts" so we know everything in the document is updated atomically and committed at the same time. There's varying approaches and lots of them. Also, just because MongoDB has the big "now with transactions" badge on it does not instantly make it a very wise idea to start writing commits over multiple documents and collections. And as for "server script", then you're looking in the wrong place. – Neil Lunn Jun 02 '18 at 08:59
  • @NeilLunn Maybe you misunderstood, I am not using MongoDB just because it recently added transactions. I merely use it because of the massive performance improvements and ease of use. I dont think you quite anwsered my question though as my issue isnt with writing to multiple documents atomically but rather with reading and then writing without having data altered in between. If there is a (much) better fit to my use case (high traffic, many games) then I will surely go with it. I remember reading that there are many ways to use denormalization to acheive this kind of functionality. – ThatBrianDude Jun 02 '18 at 09:08
  • I don't think I misunderstood at all, and I'm pretty sure if there was something "groundbreaking" to say then it would be written on the referenced existing answer. As for MongoDB 4.0 is **is not released yet** and neither is any API fully ratified, so this is not the time or place to be discussing that implementation. – Neil Lunn Jun 02 '18 at 09:11

0 Answers0