Thuta Learning
IntermediateDevOps & ToolsIntermediate

Writing Data (Set)

Firebase TutorialLesson 13

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 });

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.

Writing Data (Set) | Thuta Learning