Java – Firestore – Checks if the document being updated exists

Firestore – Checks if the document being updated exists… here is a solution to the problem.

Firestore – Checks if the document being updated exists

As far as I know – in order to check if the document exists, I should use the get function to see if it exists.

My question is about checking on update – is this possible? (Consider that when an update occurs, the documentation may disappear).

I’m trying to update an empty document, but I’m getting an error that the document doesn’t exist, but I don’t think this might be a successful way to check for this issue.

Solution

There are several ways to write data to Cloud Firestore:

  • update() – Change the fields of an existing document. Fails if the document does not exist.
  • set() – Overwrites the data in the document and creates the document if it does not exist. If you only want to partially update the documentation, use SetOptions.merge().
  • create() – only available in the server-side SDK, similar to set() but fails if the document already exists.

So you just need to use the right action for your use case. If you want to update the document without knowing if it exists, you want to use the set() and merge() options, like this (in this case Java):

// Update one field, creating the document if it does not already exist.
Map<String, Object> data = new HashMap<>();
data.put("capital", true);

db.collection("cities").document("BJ")
        .set(data, SetOptions.merge());

Related Problems and Solutions