0
0
Firebasecloud~5 mins

Nested objects and arrays in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to store complex data like lists or groups inside your database. Nested objects and arrays let you keep related information together in one place, making it easier to organize and find later.
When you want to save a user's profile with multiple addresses inside one record.
When you need to store a list of items someone bought in a single order.
When you want to keep comments and replies grouped under a post.
When you want to save settings that have multiple options inside one document.
When you want to store a collection of tags or labels for an article.
Commands
This command saves a user document with nested objects and arrays: the contacts object has an email and a list of phone numbers.
Terminal
firebase firestore:documents:set users/user123 '{"name": "Alice", "contacts": {"email": "alice@example.com", "phones": ["123-4567", "987-6543"]}}'
Expected OutputExpected
✔ Document users/user123 has been created or overwritten.
--merge - To add or update fields without overwriting the whole document
This command retrieves the user document to check that the nested objects and arrays were saved correctly.
Terminal
firebase firestore:documents:get users/user123
Expected OutputExpected
{ "name": "Alice", "contacts": { "email": "alice@example.com", "phones": [ "123-4567", "987-6543" ] } }
This command updates the phones array inside the nested contacts object without changing other fields.
Terminal
firebase firestore:documents:update users/user123 '{"contacts.phones": ["111-2222", "333-4444"]}'
Expected OutputExpected
✔ Document users/user123 has been updated.
Retrieve the document again to confirm the phones array was updated inside the nested object.
Terminal
firebase firestore:documents:get users/user123
Expected OutputExpected
{ "name": "Alice", "contacts": { "email": "alice@example.com", "phones": [ "111-2222", "333-4444" ] } }
Key Concept

If you remember nothing else from this pattern, remember: nested objects and arrays let you group related data inside one document for easier access and updates.

Common Mistakes
Trying to update a nested field without using dot notation.
The update command treats the whole field as a string key, so it overwrites the nested object instead of just the inner field.
Use dot notation like 'contacts.phones' to update only the nested array inside the object.
Passing nested data as a string without proper JSON format.
Firebase commands expect valid JSON; incorrect formatting causes errors or wrong data storage.
Always use valid JSON with double quotes and proper brackets for objects and arrays.
Summary
Use nested objects and arrays to store complex related data inside one document.
Use dot notation to update nested fields without overwriting the whole object.
Always check your data with get commands to confirm the structure is correct.