Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore: difference between set() and add()

What is the difference between set() and add() in Firestore?

I use the set() to add documents to my collection. But I am unable to use add() or understand add() from docs.

like image 980
Crazzi_Boii Avatar asked Nov 24 '17 13:11

Crazzi_Boii


People also ask

What is the difference between set and update in firebase?

In RESTful terms “set” is like an PUT, and an “update” is like a PATCH, but there is a bit more interesting distinctions under the covers. Firebase… pirate…. PATCH… get it?

Can I add to an array firestore?

When it comes to the official documentation regarding how to update elements in an array in Firestore, it says that: If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present.


1 Answers

Since you didn't specify, I'm going to assume you mean set() on DocumentReference, and add() on CollectionReference.

When you use set() on a DocumentReference, you're putting data into a document that you're already identified by some unique id. (Otherwise, you wouldn't already have a DocumentReference object!) As it says in the docs, "If the document does not yet exist, it will be created." If the document already exists, you're either replacing or merging new data into it.

When you use add() on a CollectionReference, you're unconditionally creating a new document in a collection, and that new document will have a unique id assigned to it. The data you pass will become the contents of the new document.

like image 97
Doug Stevenson Avatar answered Oct 01 '22 11:10

Doug Stevenson