owdji
owdji

Reputation: 371

Collection references must have an odd number of segments

I am currently encountering this problem in my react native app using Firebase:

Collection references must have an odd number of segments

I've seen similar cases in stackoverflow but wasn't able to solve my problem. Here is my code :

  const getData = async () => {
    console.log(user.uid + " 🚧🚧🚧")
    const col = collection(db, "users", user.uid)
    const taskSnapshot = await getDoc(col)

    console.log(taskSnapshot)
  }

  getData()

I am trying to open my document with the document reference (user.uid) but I am getting this error : Collection references must have an odd number of segments

Hope you can help me solve this problem.

Upvotes: 0

Views: 1030

Answers (2)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

replace this

collection(db, "users", user.uid)

with this

collection(db).document("users").collection(user.uid)

Upvotes: 0

Dharmaraj
Dharmaraj

Reputation: 50840

The getDoc() takes a DocumentReference as parameter and not a CollectionReference so you must use doc() instead of collection().

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

const docRef = doc(db, "users", user.uid)
const taskSnapshot = await getDoc(col)
console.log(taskSnapshot.data() || "Doc does not exists")

Also checkout Firestore: What's the pattern for adding new data in Web v9?

Upvotes: 1

Related Questions