Thuta Learning
IntermediateDevOps & Toolsintermediate

Adding Data (Add)

Relax. We'll talk through this in plain words — no textbook voice.

Adding Data (Add)

addDoc lets Firebase auto-generate the document ID for you. It's handy when you're adding new items one at a time, like notes, posts, orders, or messages.

Code Example

javascript
import { getFirestore, collection, addDoc, serverTimestamp } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';

const db = getFirestore();
const auth = getAuth();

async function createNote(title, content) {
  const user = auth.currentUser;
  if (!user) throw new Error('Login required');

  const docRef = await addDoc(collection(db, 'notes'), {
    ownerId: user.uid,
    title: title,
    content: content,
    createdAt: serverTimestamp(),
    isPinned: false
  });

  console.log('New note ID:', docRef.id);
}

What should you watch out for?

serverTimestamp() is more reliable because it saves the server's time instead of trusting the user's device clock. It's useful for data where the created time matters, like orders, posts, or chat messages.

Expected outputNew note ID: Lk9aPq82xYzExample

Adding Data (Add) | Thuta Learning