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.
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.
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!
If either the collection or document does not exist, Cloud Firestore creates it.
There are a few ways to write data to Cloud Firestore:
SetOptions.merge()
.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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With