Home > Net >  How to update a document by ID using Firebase Modular SDK (V9)?
How to update a document by ID using Firebase Modular SDK (V9)?

Time:03-19

This code creates a new document every time the user logs in but my task is to update existing same user ID document if it exists else create a new one. How can I do that in V9 Firebase?

Current Code

setDoc(
  query(collectionRef),
  //     db.collection('users').doc(user.uid).set(

  {
    email: user.email,
    lastSeen: serverTimestamp(),
    photoURL: user.photoURL
  }, {
    merge: true
  }
);

Old Code that access document UID:

CodePudding user response:

The first parameter in setDoc() should be DocumentReference:

import { doc, setDoc } from "firebase/firestore"

const docRef = doc(db, "users", user.uid);

setDoc(docRef, {
  email: user.email,
  lastSeen: serverTimestamp(),
  photoURL: user.photoURL
}, {
  merge: true
}).then(() => console.log("Document updated"));
  • Related