0
0
FirebaseHow-ToBeginner · 3 min read

How to Add a Document in Firestore: Simple Guide

To add a document in Firestore, use the add() method on a collection reference to create a new document with an auto-generated ID, or use set() on a document reference to specify the ID. Both methods require passing an object with the data you want to store.
📐

Syntax

There are two main ways to add a document in Firestore:

  • Using add(): Adds a new document with an auto-generated ID to a collection.
  • Using set(): Creates or overwrites a document with a specified ID.

Both methods require passing an object with the data fields and values.

javascript
const docRef = await firestore.collection('collectionName').add({ field1: 'value1', field2: 42 });

await firestore.collection('collectionName').doc('customDocId').set({ field1: 'value1', field2: 42 });
💻

Example

This example shows how to add a new document with an auto-generated ID and how to add a document with a custom ID in Firestore using Firebase JavaScript SDK.

javascript
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, addDoc, doc, setDoc } from 'firebase/firestore';

const firebaseConfig = {
  apiKey: 'your-api-key',
  authDomain: 'your-auth-domain',
  projectId: 'your-project-id'
};

const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app);

async function addDocuments() {
  // Add document with auto-generated ID
  const docRef = await addDoc(collection(firestore, 'users'), {
    name: 'Alice',
    age: 30
  });
  console.log('Document added with ID:', docRef.id);

  // Add document with custom ID
  await setDoc(doc(firestore, 'users', 'user_123'), {
    name: 'Bob',
    age: 25
  });
  console.log('Document with custom ID added');
}

addDocuments();
Output
Document added with ID: <auto-generated-id> Document with custom ID added
⚠️

Common Pitfalls

Common mistakes when adding documents in Firestore include:

  • Forgetting to await asynchronous calls, causing unexpected behavior.
  • Using set() without specifying a document ID, which will fail.
  • Not initializing Firebase app or Firestore properly before calling methods.
  • Passing data that contains unsupported types or circular references.
javascript
/* Wrong: Missing await, no error handling */
firestore.collection('users').add({ name: 'Eve' });

/* Right: Await the promise and handle errors */
try {
  const docRef = await firestore.collection('users').add({ name: 'Eve' });
  console.log('Added with ID:', docRef.id);
} catch (error) {
  console.error('Error adding document:', error);
}
📊

Quick Reference

Use this quick reference to remember how to add documents:

MethodDescriptionWhen to Use
add()Adds document with auto-generated IDWhen you don't need to specify ID
set()Creates or overwrites document with custom IDWhen you want to control document ID

Key Takeaways

Use add() to add a document with an auto-generated ID to a collection.
Use set() with a document reference to specify a custom document ID.
Always await Firestore calls to ensure data is written before proceeding.
Initialize Firebase and Firestore properly before adding documents.
Avoid unsupported data types and handle errors when adding documents.