How to Add a Document to Firestore: Simple Guide
To add a document to Firestore, use the
add() method on a collection reference to create a new document with an auto-generated ID, or use doc().set() to specify a custom ID. This stores your data as key-value pairs in Firestore.Syntax
Use collection('collectionName').add(data) to add a document with an auto-generated ID. Use collection('collectionName').doc('customId').set(data) to add a document with a specific ID.
collection('collectionName'): selects the collection to add the document to.
add(data): adds a new document with auto ID.
doc('customId'): selects or creates a document with the given ID.
set(data): writes data to the document.
javascript
const docRef = firestore.collection('users').add({ name: 'Alice', age: 30 }); const customDocRef = firestore.collection('users').doc('user123').set({ name: 'Bob', age: 25 });
Example
This example shows how to add a new user document to the users collection with an auto-generated ID, then log the new document's ID.
javascript
import { initializeApp } from 'firebase/app'; import { getFirestore, collection, addDoc } 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 addUser() { try { const docRef = await addDoc(collection(db, 'users'), { name: 'Alice', age: 30 }); console.log('Document written with ID:', docRef.id); } catch (e) { console.error('Error adding document:', e); } } addUser();
Output
Document written with ID: <auto-generated-id>
Common Pitfalls
- Not initializing Firestore before adding documents causes errors.
- Using
set()without specifying a document ID overwrites the whole collection reference, which is invalid. - Forgetting to handle asynchronous calls with
awaitorthen()can lead to unexpected behavior. - Trying to add data with unsupported types or circular references will fail.
javascript
/* Wrong: Missing await causes no confirmation */ firestore.collection('users').add({ name: 'Alice' }); /* Right: Use await to wait for completion */ await firestore.collection('users').add({ name: 'Alice' });
Quick Reference
| Method | Description | When to Use |
|---|---|---|
| add(data) | Adds a new document with auto-generated ID | When you don't need a custom document ID |
| doc(id).set(data) | Creates or overwrites a document with a specific ID | When you want to control the document ID |
| set(data, { merge: true }) | Updates fields without overwriting the whole document | When updating existing documents partially |
Key Takeaways
Use collection().add(data) to add documents with auto-generated IDs.
Use collection().doc(id).set(data) to add or overwrite documents with custom IDs.
Always initialize Firestore before adding documents.
Handle asynchronous calls properly with async/await or promises.
Avoid unsupported data types and remember Firestore stores data as key-value pairs.