Google firestore rest API: How to create documents within a transaction

Viewed 141

Using a transaction ref I can update multiple documents by creating an array/list of Write objects and then doing a CommitRequest.

However I can find no way of creating new documents within the transaction? firestoreApi.projects.databases.documents.createDocument(...) Doesn't provide have a transaction parameter. Write seems to for updating documents and not creating new ones.

1 Answers

Creating documents from a transaction is definitely possible. You would first need to begin a new transaction using the projects.databases.documents.beginTransaction endpoint. After using the beginTransaction endpoint, you will receive a transaction ID that can be used with the projects.databases.documents.commit endpoint. This endpoint does use a Write object, but the Write object has a currentDocument property which is a Precondition type. The Precondition object in turn has a property called exists, which needs to be set to false so that it can be declared that a document does not exist.

When it is set to true, the target document must exist. When it is set to false, the target document must not exist.

This allows a new document to be created from the transaction, and then the transaction is committed.

Related