0
0
Firebasecloud~5 mins

Writing data (set, update, push) in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you want to save or change information in a Firebase database, you use writing commands. These commands let you add new data, change existing data, or add data with a unique ID automatically.
When you want to save a new user's profile information in your app.
When you need to change the status of an order in your database.
When you want to add a new message to a chat without overwriting others.
When you want to update only part of a user's settings without changing the rest.
When you want to add data with a unique key generated automatically.
Commands
This command sets the data at the path /users/user1 to the given JSON object. It creates or replaces the data at that location.
Terminal
firebase database:set /users/user1 '{"name":"Alice","age":30}'
Expected OutputExpected
✔ Data at /users/user1 set successfully.
This command updates only the age field of the user1 data without changing other fields like name.
Terminal
firebase database:update /users/user1 '{"age":31}'
Expected OutputExpected
✔ Data at /users/user1 updated successfully.
This command adds a new message under /messages with a unique key generated automatically, so it does not overwrite existing messages.
Terminal
firebase database:push /messages '{"text":"Hello!","sender":"user1"}'
Expected OutputExpected
✔ Data pushed to /messages with key -Mxyz123abc.
This command retrieves the current data at /users/user1 to verify the changes made by set or update.
Terminal
firebase database:get /users/user1
Expected OutputExpected
{ "name": "Alice", "age": 31 }
Key Concept

If you remember nothing else from this pattern, remember: set replaces data, update changes parts of data, and push adds new data with a unique key.

Common Mistakes
Using set when you want to add data without deleting existing data.
Set replaces all data at the path, so existing data will be lost.
Use update to change parts of data or push to add new entries without overwriting.
Using push when you want to update existing data at a known path.
Push always creates a new unique key, so it won't update existing data.
Use update or set with the exact path to modify existing data.
Summary
Use 'set' to create or replace data at a specific path.
Use 'update' to change only certain fields without removing others.
Use 'push' to add new data with a unique key automatically.
Verify changes by retrieving data with 'get' command.