0
0
Firebasecloud~30 mins

Creating collections and documents in Firebase - Try It Yourself

Choose your learning style9 modes available
Creating collections and documents
📖 Scenario: You are building a simple app to store user profiles in a cloud database. Each user has a name and an email address. You will create a collection called users and add documents for each user.
🎯 Goal: Create a Firestore collection named users and add user documents with name and email fields.
📋 What You'll Learn
Create a Firestore collection called users
Add a document for a user with name and email fields
Add a second user document with the same fields
Use Firestore's setDoc method to add documents
💡 Why This Matters
🌍 Real World
Storing user profiles or any structured data in a cloud database for web or mobile apps.
💼 Career
Understanding how to create collections and documents in Firestore is essential for backend and full-stack developers working with Firebase.
Progress0 / 4 steps
1
Initialize Firestore and create the users collection reference
Write code to initialize Firestore and create a collection reference called usersRef for the users collection.
Firebase
Need a hint?

Use collection(db, 'users') to create the collection reference.

2
Create a user object to add
Create a constant object called user1 with name set to 'Alice' and email set to 'alice@example.com'.
Firebase
Need a hint?

Use const user1 = { name: 'Alice', email: 'alice@example.com' }.

3
Add the first user document to the users collection
Write code to add user1 as a document to the usersRef collection using the setDoc method with a document reference named user1Doc created by doc(usersRef, 'user1').
Firebase
Need a hint?

Use doc(usersRef, 'user1') to create the document reference and setDoc to add the data.

4
Add a second user document to the users collection
Create a constant object called user2 with name set to 'Bob' and email set to 'bob@example.com'. Then create a document reference called user2Doc using doc(usersRef, 'user2') and add user2 to the collection using setDoc.
Firebase
Need a hint?

Repeat the steps for user1 but with user2 and user2Doc.