Thuta Learning
IntermediateDevOps & ToolsIntermediate

Adding Data (Add)

Firebase TutorialLesson 14

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

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Adding Data (Add) | Thuta Learning