简体   繁体   中英

Firestore addDoc error:Invalid document reference. Document references must have an even number of segments, but

I would like to save my data to firestore in React.js app but Firestore returns me Invalid document reference. Document references must have an even number of segments, but

Firebase Config file

import { initializeApp,} from "firebase/app";
import {getAuth} from 'firebase/auth'
import {getFirestore} from "firebase/firestore"

const firebaseConfig = {
    apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
    appId:process.env.REACT_APP_FIREBASE_APP_ID,
    measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
  };

  const app =initializeApp(firebaseConfig);
  export const db=getFirestore(app);
  export const auth= getAuth(app)

and it is my code for saving data to firebase with addDoc

    try{ 
        const user = await createUserWithEmailAndPassword(auth,email,password);
         const data={
            userId:user.user.uid,
            name: "Pls set name",
            about:"Pls set about",
            profileImg:"",
            contacts:[
                "",
            ]
        }
        const docRef =doc(collection(db,`/users/`));
        await addDoc(docRef,data);
        return user
    }catch(err){
        console.log(err.message)
    }

lastly screenshot of error

在此处输入图像描述

It's customary to use the user's UID as the document ID when creating per-user documents, so that they are easy to find later for that user. Your code is currently generating two random strings for document IDs, which is definitely not what you want. The first random ID is coming from your call to doc() , then again from your call to addDoc() .

To use the UID as the document ID, follow along with the documentation :

await setDoc(doc(db, "users", user.user.uid), data);

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