What is the equivalent of getDocFromServer for setDoc in Firestore? To confirm that the doc is saved on the server and not cache

Viewed 169

This is a rather basic and simple task, but it seems as though firestore has no feature for it for some reason.

In my app, it's vital that the information being saved to the database is confirmed to be saved on the server. I simply want to make setDoc return a success or a failure whether it writes to the server or not. However, it seems that firestore's model is that setDoc will return success even if it only writes to cache (pending future server write - which may not go through). This makes sense to have seamless offline functionality and overall I think it's a good idea. However not for this particular use case.

Firestore transactions seem to be ideal - failing if there is no connectivity to the server, and only succeeding if actually written to the server. However the problem with transactions is that they require the document to be there already. I can't set a transaction to a new document like I can with setDoc - which will create one if there isn't one already.

A workaround would be to do a setDoc prior to the transaction, but then it do two writes for every save, doubling the cost of running it.

Is there really no simple setDocFromServer ?

1 Answers

However the problem with transactions is that they require the document to be there already. I cannot set a transaction to a new document like I can with setDoc - which will create one if there is not one already.

Firestore transactions support creating new documents when the document does not currently exist. By using the documents.beginTransaction endpoint of the API, you can get a new transaction ID. This transaction ID can be used with the documents.commit endpoint to commit a document. This end point consists of a Write object, which itself has several parameters you must configure. One relevant for this requirement is the Precondition object, which contains an exists property. The exists property is used to declare if the document to commit already exists or not in the database:

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

By setting the exists property to false, a new document is created from this transaction. I have previously tested this behavior on a related thread.

Related