Thuta Learning
IntermediateDevOps & Toolsintermediate

Writing Data (Set)

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

Writing Data (Set)

setDoc lets you pick the document ID yourself and save data under it. It's useful for data where you want a predictable ID, like a user profile.

Code Example

javascript
import { getFirestore, doc, setDoc } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';

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

async function saveProfile() {
  const user = auth.currentUser;
  if (!user) return;

  await setDoc(doc(db, 'users', user.uid), {
    name: 'Sai',
    email: user.email,
    role: 'student'
  });

  console.log('Profile saved');
}

What does this code do?

doc(db, 'users', user.uid) uses the logged-in user's UID as the document ID inside the users collection. Storing it this way keeps things simple: one user equals one profile document.

Common mistake

setDoc replaces the whole document by default. If you don't want to lose existing fields, use { merge: true }.

javascript
await setDoc(doc(db, 'users', user.uid), {
  lastLoginAt: new Date()
}, { merge: true });
Writing Data (Set) | Thuta Learning