Tal Barda
Tal Barda

Reputation: 4287

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.

Upvotes: 13

Views: 15920

Answers (5)

Abdur Rehman
Abdur Rehman

Reputation: 555

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))

Upvotes: 0

Jan Jarčík
Jan Jarčík

Reputation: 2901

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  
}

Upvotes: 2

AmitNayek
AmitNayek

Reputation: 178

We can go with update and set the mask parameter to true like this: -

firestore.updateDocument("GFrom/"+data.email,data, true);

Upvotes: 0

Sam Stern
Sam Stern

Reputation: 25134

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());

Upvotes: 30

Gil Gilbert
Gil Gilbert

Reputation: 7870

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.

Upvotes: 9

Related Questions