Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Firestore how to update a field in a document that may or may not exist?

If we try to update a field in a document in Firestore, it throws an error, that it doesn't exist. Should I manually first check the document exist, and if not, create it and then update the field, or there is a better and more elegant practice?

like image 737
Hamoonist Avatar asked Oct 22 '18 16:10

Hamoonist


People also ask

Is there any way to update a specific index from the array in firestore?

Is there any way to update a specific index from the array in Firestore? No, there is not! This is not possible because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, the things are different that you might think.

Does firestore Create collection if not exists?

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


1 Answers

You haven't said which language you're using to write your code, but each SDK should have an option to pass to set() that lets you update a document that already exists. For example, in JavaScript on web clients:

doucmentReference.set({ a: 1 }, { merge: true })

That merge: true will update the data if the document already exists.

like image 187
Doug Stevenson Avatar answered Sep 21 '22 19:09

Doug Stevenson