KaganBerk
KaganBerk

Reputation: 110

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

enter image description here

Upvotes: 0

Views: 419

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317497

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

Upvotes: 3

Related Questions