title: Firebase - how to run a query and an update on a document in one transaction
body: <p>My problem is that transactions only allow to <code>delete</code>, <code>get</code>, <code>set</code> and <code>update</code> documents.</p>
  
  <p>For a 2 player game I need to create games and to join a game. The idea is following:</p>
  
  <ul>
  <li>check if a game without opponent exists => join it if I find one</li>
  <li>create a new game if no game without opponent exists</li>
  </ul>
  
  <p>This means, that the query that searches for a game without opponent and updates it runs in a transaction. How can I do this?</p>
  
  <p><strong>Problem:</strong></p>
  
  <p><em>What if the game did change in the meantime (between query and update) and was updated already? I currently possibly override some other player who has joined the game in the meantime... How can I solve this problem?</em></p>
  
  <p><strong>Code</strong></p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>// get a game without opponent
  var gameQueryRef = db.collection('games')
      .where('state', '==', '1')
      .limit(1);
  
  return gameQueryRef.get()
      .then(querySnapshot =&gt; {
          var gameRef = null;
          if (querySnapshot.docs.length === 0) {
              return null;
          } else {
              return querySnapshot.docs[0].ref;   
          }
      })
      .then(gameRef =&gt; {
          log("GameRequest", gameRequestId, "gameRef = " + gameRef);
          if (gameRef === null)
          {
              var newGameRef = db.collection("games").doc();
              var game = {
                  state: 1,
                  creationDate: Date.now(),
                  finishDate: 0,
                  docPlayer1: docPlayer,
                  docPlayer2: null
              };
              return newGameRef.set(game);
          }
          else
          {
              // update game =&gt; THIS IS NOT SAVE!
              // what if the game did change in the meantime and was updated already????
              // I possibly override some other player who has joined this game in the meantime...
              return gameRef.update(state =&gt; 2, docPlayer2 =&gt; docPlayer);
          }
      })
      // continue with game
  </code></pre>
  
  <p><strong>EDIT - Solution</strong></p>
  
  <p>I posted a possible solution I will test, if someone has a comment on this I'm interested in this as well.</p>