Skip to content Skip to sidebar Skip to footer

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 possi

Solution 1:

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 = newHashMap<>();
data.put("capital", true);

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

Solution 2:

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.

Solution 3:

Solution 4:

The easiest way to try to update a document that does not exist is:

try {
  await db.collection('cities').doc('BJ').update('key', 'value')
} catch (error) {
  // document not exists, do nothing  
}

Solution 5:

I think in such type of scenario the set() with merge: true is the best option to use. Using Flutter

firestoreInstance.collection("users").doc(firebaseUser.uid).set(
{
"username" : "userX",
},SetOptions(merge: true))

Post a Comment for "Firestore - Check If The Document Which Is Being Updated Exists"