Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create firestore transaction where target document needs to be found

Tags:

I am looking for a way to create a firestore transaction where i find a document from a query and then modify this document in a transaction.

Something along those lines (kotlin):

firestore.runTransaction { transaction ->

  val snapshot = transaction.get(db.collection("document")
      .whereEqualTo("someField", null)
      .orderBy("creationDate", ASCENDING)
      .limit(1L))

  val myObject = snapshot.toObject(MyObject::class.java)
  myObject.someFiled = "123"
  transaction.set(snapshot.reference, myObject)
}

The problem here is that the query returned by the .limit(1) method is not a DocumentReference, which is the only type the transaction accepts. Therefore my question is, how can such a transaction be achieved in java/kotlin?

I have seen something similar in this blog post using the admin sdk:

  return trs.get(db.collection('rooms')
    .where('full', '==', false)
    .where('size', '==', size)
    .limit(1));
like image 460
Moritz Avatar asked Dec 06 '17 16:12

Moritz


People also ask

Does firestore Create collection if not exists?

If either the collection or document does not exist, Cloud Firestore creates it.

How do I use getDoc for firestore?

Firebase 9 Firestore Get A Document By ID Using getDoc() Let's get the first document of the cities collection by id. Import Firestore Database and de-structure the three methods that we need: getFirestore() → Firestore Database. doc() → It takes references of database, collection name and ID of a document as arguments.

Is there any way to update a specific index from the array in firestore?

Is there any way to update a specific index from the array in Firestore? No, there is not! This is not possible because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, the things are different that you might think.

How do I get firestore to fetch data?

Reading data from Firestore There are two ways for retrieving data, which is stored in Cloud Firestore. Calling a method to get the data. Setting a listener for receiving data changes events. We send an initial snapshot of the data, and then another snapshot is sent when the document changes.


1 Answers

After investigation looks like you can't do that in Kotlin/Java it is not supported. You will have to create cloud function and do something similar to:

exports.executeTransaction = functions.https.onRequest(async (req, res) => {

    const db = admin.firestore();

    const query = db
        .collection('collection')
        .where('name', '==', 'name')
        .limit(1);

    db.runTransaction(transaction => {
        return transaction
            .get(query)
            .then((querySnapshot) => {
                const gameDocSnapshot = querySnapshot.docs[0];
                const gameData = gameDocSnapshot.data();
                transaction.update(gameDocSnapshot.ref, { name: 'change' });
                return gameData;
            })
    })
        .then((gameData) => {
            res.send(gameData);
            console.log('Transaction successfully committed!', gameData);
        })
        .catch((error) => {
            res.send('Transaction failed:' + error);
            console.log('Transaction failed:', error);
        });
});
like image 114
5er Avatar answered Sep 22 '22 13:09

5er