Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - Check if the document which is being updated exists

As far as I know - In order to check whether a document exists or not, I should use the get function and see if it does.

My question is about checking while updating - Is it possible? (Considering that the document might be gone when the update occurs).

I have tried to update an empty document and I got an error which says that the document doesn't exist, but I think this might not be the successful way to check this.

like image 794
Tal Barda Avatar asked Oct 11 '17 19:10

Tal Barda


People also ask

How do I listen to changes on firestore?

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

How do I get most recent documents on firestore?

Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!

Does firestore Create collection if not exists?

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


2 Answers

There are a few ways to write data to Cloud Firestore:

  • update() - change fields on a document that already exists. Fails if the document does not exist.
  • set() - overwrite the data in a document, creating the document if it does not already exist. If you want to only partially update a document, use SetOptions.merge().
  • create() - only available in the server-side SDKs, similar to set() but fails if the document already exists.

So you just need to use the correct operation for your use case. If you want to update a document without knowing if it exists or not, you want to use a set() with the merge() option like this (this example is for 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());
like image 62
Sam Stern Avatar answered Sep 29 '22 09:09

Sam Stern


If you only want to perform an update if the document exists, using update is exactly the thing to do. The behavior you observed is behavior you can count on.

We specifically designed this so that it's possible to perform a partial update of a document without the possibility of creating incomplete documents your code isn't otherwise prepared to handle.

like image 24
Gil Gilbert Avatar answered Sep 29 '22 11:09

Gil Gilbert