0
0
Firebasecloud~5 mins

Adding documents (add vs set) in Firebase - CLI Comparison

Choose your learning style9 modes available
Introduction
When you want to save information in Firebase Firestore, you can add new documents in two main ways: using add or set. Both save data but work a bit differently on how they create or update documents.
When you want Firebase to create a new document with a unique ID automatically.
When you want to specify the exact ID for the document you are saving.
When you want to add a new document without worrying about overwriting existing data.
When you want to update or replace data in a document with a known ID.
When you want to merge new data into an existing document without deleting other fields.
Commands
This command adds a new document with a unique ID to the 'users' collection with the given data.
Terminal
firebase firestore:documents:add users '{"name":"Alice","age":30}'
Expected OutputExpected
Document added with ID: XyZ123AbC
This command sets the document with ID 'user123' in the 'users' collection to the given data, replacing any existing data.
Terminal
firebase firestore:documents:set users/user123 '{"name":"Bob","age":25}'
Expected OutputExpected
Document users/user123 successfully written.
This command updates the 'age' field in the 'user123' document without deleting other fields by merging the new data.
Terminal
firebase firestore:documents:set users/user123 '{"age":26}' --merge
Expected OutputExpected
Document users/user123 successfully written.
--merge - Merges new data with existing document fields instead of replacing.
This command lists documents in the 'users' collection so you can verify the data was added or updated.
Terminal
firebase firestore:documents:list users
Expected OutputExpected
Document ID: XyZ123AbC name: Alice age: 30 Document ID: user123 name: Bob age: 26
Key Concept

If you remember nothing else from this pattern, remember: use add to create new documents with automatic IDs, and use set to create or update documents with specific IDs.

Common Mistakes
Using set without --merge when updating a document.
This replaces the entire document and deletes any fields not included in the new data.
Use set with the --merge flag to update only specific fields without deleting others.
Using add when you want to control the document ID.
Add always creates a new document with a random ID, so you cannot specify the ID.
Use set with the document ID path to specify the exact document to create or update.
Summary
Use 'add' to create new documents with unique IDs automatically generated by Firebase.
Use 'set' to create or overwrite documents with a specific ID you choose.
Use 'set' with the '--merge' flag to update parts of a document without deleting existing fields.