0
0
Firebasecloud~5 mins

Setting with merge option in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you update data in Firebase Firestore, sometimes you want to add or change only some parts without removing the rest. The merge option helps you update specific fields without deleting existing data.
When you want to add a new field to a document without removing existing fields.
When you want to update some fields in a document but keep other fields unchanged.
When you want to avoid overwriting the entire document accidentally.
When you want to combine new data with existing data safely.
When you want to update nested fields without replacing the whole nested object.
Commands
This command updates the document 'user123' in the 'users' collection by adding or updating the fields 'age' and 'city' without deleting other existing fields, thanks to the --merge flag.
Terminal
firebase firestore:documents:set users/user123 '{"age": 30, "city": "New York"}' --merge
Expected OutputExpected
✔ Document users/user123 updated with merge option.
--merge - Ensures only specified fields are updated, existing fields remain untouched.
This command retrieves the current data of the document 'user123' to verify that the merge update worked and other fields are still present.
Terminal
firebase firestore:documents:get users/user123
Expected OutputExpected
{ "age": 30, "city": "New York", "name": "Alice", "email": "alice@example.com" }
Key Concept

If you remember nothing else from this pattern, remember: the merge option updates only specified fields without deleting the rest of the document.

Common Mistakes
Updating a document without the --merge flag when you want to keep existing fields.
This overwrites the entire document, deleting fields not included in the update.
Always use --merge when you want to update specific fields without removing others.
Using incorrect JSON syntax in the update command.
The command fails because Firebase expects valid JSON for the data.
Use proper JSON format with double quotes around keys and string values.
Summary
Use the --merge flag to update only specific fields in a Firestore document.
Without --merge, updates overwrite the entire document, removing unspecified fields.
Verify updates by retrieving the document after applying changes.