How to Create a Collection in Firestore: Simple Guide
In Firestore, you create a collection by adding a document to it using
collection() and doc() methods. Collections are created automatically when you add the first document with set() or add().Syntax
To create a collection in Firestore, you use the collection() method to specify the collection name, then add a document with doc() or add(). The collection is created automatically when the first document is added.
collection('collectionName'): selects or creates the collection.doc('documentId'): specifies the document ID (optional).set(data): writes data to the document.add(data): adds a new document with an auto-generated ID.
javascript
const db = firebase.firestore(); db.collection('collectionName').doc('documentId').set({ key: 'value' });
Example
This example shows how to create a collection named users and add a document with a specific ID and data.
javascript
import { initializeApp } from 'firebase/app'; import { getFirestore, collection, doc, setDoc } from 'firebase/firestore'; const firebaseConfig = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN', projectId: 'YOUR_PROJECT_ID' }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); async function createUser() { const usersCollection = collection(db, 'users'); const userDoc = doc(usersCollection, 'user123'); await setDoc(userDoc, { name: 'Alice', age: 30 }); console.log('User document created in users collection'); } createUser();
Output
User document created in users collection
Common Pitfalls
Common mistakes when creating collections in Firestore include:
- Trying to create a collection without adding a document first — collections are created only when a document is added.
- Using
doc()withoutset()oradd()means no data is saved. - Not initializing Firebase app before accessing Firestore.
javascript
const db = firebase.firestore(); // Wrong: This does NOT create a collection because no document is added const users = db.collection('users'); // Right: Add a document to create the collection users.doc('user1').set({ name: 'Bob' });
Quick Reference
Summary tips for creating collections in Firestore:
- Use
collection('name')to specify the collection. - Add documents with
doc('id').set(data)oradd(data). - Collections are created automatically when the first document is added.
- Always initialize Firebase before using Firestore.
Key Takeaways
Firestore collections are created automatically when you add the first document.
Use collection() to select the collection and set() or add() to add documents.
You must initialize Firebase before accessing Firestore.
Creating a collection without adding a document does nothing.
Use doc('id').set(data) for custom document IDs or add(data) for auto IDs.