0
0
Firebasecloud~5 mins

Creating collections and documents in Firebase - Step-by-Step CLI Walkthrough

Choose your learning style9 modes available
Introduction
When you want to store data in Firebase Firestore, you organize it into collections and documents. Collections hold documents, and documents hold your actual data. This helps keep your data neat and easy to find.
When you want to save user profiles in your app.
When you need to store messages in a chat application.
When you want to keep track of orders in an online store.
When you want to save settings or preferences for each user.
When you want to add new data entries without changing existing ones.
Commands
This command creates a document with ID 'user123' inside the 'users' collection and adds the fields 'name' and 'age' with their values.
Terminal
firebase firestore:documents:create users/user123 --data '{"name":"Alice","age":30}'
Expected OutputExpected
Document users/user123 created successfully.
--data - Specifies the JSON data to store in the document.
This command retrieves and shows the data stored in the document 'user123' inside the 'users' collection to verify it was created correctly.
Terminal
firebase firestore:documents:get users/user123
Expected OutputExpected
{ "name": "Alice", "age": 30 }
Creates another document 'user124' in the 'users' collection with different data to show how to add multiple documents.
Terminal
firebase firestore:documents:create users/user124 --data '{"name":"Bob","age":25}'
Expected OutputExpected
Document users/user124 created successfully.
--data - Specifies the JSON data to store in the document.
Lists all collections in your Firestore database to confirm the 'users' collection exists.
Terminal
firebase firestore:collections:list
Expected OutputExpected
users
Key Concept

If you remember nothing else from this pattern, remember: collections hold documents, and documents hold your data as key-value pairs.

Common Mistakes
Trying to create a document without specifying data.
Firestore requires data to create a document; otherwise, the command fails.
Always include the --data flag with valid JSON when creating a document.
Using incorrect document paths like missing collection name.
Firestore needs the full path including collection and document ID to locate or create documents.
Always specify the collection name followed by the document ID, like 'users/user123'.
Summary
Use 'firebase firestore:documents:create' with --data to add documents to collections.
Verify document creation with 'firebase firestore:documents:get'.
List collections using 'firebase firestore:collections:list' to see your data groups.