4. You want to update the user's email without removing other user data. Which Firebase method usage below contains an error?
medium
A. firebase.database().ref('users/user1').update({ email: 'new@example.com' })
B. firebase.database().ref('users/user1/email').set('new@example.com')
C. firebase.database().ref('users/user1').update({ email: 'new@example.com', phone: '1234567890' })
D. firebase.database().ref('users/user1').push({ email: 'new@example.com' })
Solution
Step 1: Understand push() usage
push() adds a new child with a unique key; it does not update existing fields.
Step 2: Analyze the goal
To update email without removing other data, update() is correct; push() wrongly adds a new child instead.
Final Answer:
Using push() to update email is incorrect -> Option D
Quick Check:
push() adds new child, not update fields [OK]
Hint: Use update() to change fields, not push() [OK]
Common Mistakes:
Using push() to update existing fields
Using set() which overwrites all data
Confusing update() and push() roles
5. You want to add multiple chat messages under 'chats' in Firebase Realtime Database, each with a unique key, and also update the user's last active timestamp without overwriting existing data. Which combination of methods should you use?
hard
A. Use push() for messages and update() for last active timestamp
B. Use push() for messages and set() for last active timestamp
C. Use update() for messages and set() for last active timestamp
D. Use set() for messages and update() for last active timestamp
Solution
Step 1: Add multiple messages with unique keys
Use push() under 'chats' to add each message with a unique key without overwriting others.
Step 2: Update last active timestamp without overwriting
Use update() on the user's data to change the timestamp without removing other fields.
Final Answer:
Use push() for messages and update() for last active timestamp -> Option A