简体   繁体   中英

How to add a document with user.uid as id to a collection in Firebase?

The first time user logs in with Google Auth provider I want to add a document with user.uid as id to "Users" collection .

If I use setDoc to add the document ,

  await setDoc(doc(db, "UsersData", user.uid), {
    username: "",
    isAdmin: false,
    user: JSON.parse(JSON.stringify(user))
  });

and the user changes the username, done with updateDoc , this ☝️ properties will be merged with the old ones everytime the user logs in.

I tried addDoc ,

  await addDoc(collection(db, "UsersData", user.uid), {
    username: "",
    isAdmin: false,
    user: JSON.parse(JSON.stringify(user))
  });

but I get this error Document references must have an even number of segments UserData... has 3 , how can I solve this?

Function addDoc() is, to adding new documents with auto generated ID. This function got just two variables, you can pass in collection reference and data. There are two ways to update documents. Using updateDoc() and setDoc() .

Using setDoc() function will create a new file if it not exists and update if it has option merge to true.

const docRef = doc(db, 'userData', user.uid)
const result = await setDoc(docRef, { name: user.displayName}, { merge: true })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM