FirebaseError: Function CollectionReference.doc() cannot be called with an empty path

Viewed 11873

I am getting a list of id's from users collection then when I am trying to get by id data from another collection anunturi this error:

FirebaseError: Function CollectionReference.doc() cannot be called with an empty path

<script>
import { db } from "../Utils/fire.js"
import { current_user } from "../Utils/auth.js"
import Room from "./Room.svelte"

async function interestedForUser(){
    let query = await db.collection("users").doc($current_user.uid).get()
    const listingsIds = await query.data().anunturi_interesat 
    console.log(listingsIds) //ok
    let anunturi = []
    for (let id of listingsIds) {
        console.log(id, typeof(id)) // ok
        let anunt = await db.collection("anunturi").doc(id).get() // nok
        let anunt_data = await anunt.data() 
        if (anunt_data) {
            anunturi.push({...anunt_data, listingId:id})
        } 
    }
    return anunturi
}

</script>

{#await interestedForUser()}
    <p class="text-center mt-12">Se incarca...</p>
{:then listings}
    {console.log("In template:", listings, listings.length)} //ok (but why?)
    {#if listings.length > 0} // this doesn't get rendered..
        {#each listings as camera }
            <Room {camera}/>
        {/each}
    {:else}
        <p class="text-center mt-12">Nu ai postat nici un anunt</p>
    {/if}
{:catch error}
    <p style="color: red">{error.message}</p>
{/await}

console error

UPDATE:

The issue was in the <Room {camera}/> component. A child of Room component had a firestore reference undefined.

5 Answers

The error message is telling you that this bit of code has a problem:

doc(String(id))

If id is already a string (we can't tell from what you show here), then just pass it directly:

doc(id)

If it is a number, and you want to convert it to a string:

doc(id.toString())

If it is something else, then you'll have to be more specific about how you want to convert it to the string of the document ID you want Firestore to use.

I've the same type of problem in Next JS when I try to fetch data of a specific id from Firebase.

Try this if you're facing issue in next js.

import React, { useState ,useEffect} from "react";
import StudentsWithID from "../../Componenets/Navbar/Form/StudentsWithID";
import firebase from 'firebase/app';

const StudentWithId = ({sid}) => {
  const [student,setStudent] =useState();
  /*
  const router = useRouter();
  const { sid } = router.query; 
  
  ^^^^^^^^^^^^^^^^^^^^^
  iiiiiiiiiiiiiiiiiiiii
  
  I try to get id of student with these lines. but It doesn't when i build the project (npm run build)
  ?: file name is [sid].js || It is not working in [id].js

  */
  useEffect(()=>{
    const loadStudent=async ()=>{
   try{
      const result= await firebase.firestore().collection("students").doc(String(""+sid.sid)).get()
      const my_student=result.data()
      if(my_student){
      setStudent(my_student)
      console.log(my_student)
    }else{
      console.log("Stundent not found")
    }
  }catch(err){
console.log("-----------------StudentError------------------")
console.log(err.message);
  }}
loadStudent()
  },[])
 
  return (
    <div>
      <StudentsWithID props={student}/>
    </div>
  );
};

export async function getServerSideProps({query,params}) {
  //todo: when I try to get id in server it works perfectly.
const sid=query||params
  return{
    props:{
      sid:sid
    }
  }

}

export default StudentWithId;

The problem is that doc() function only accepts string value. So, If you want to use string variable, you should put backticks around it with $ sign.

Like this:

export const UserOrders = (props) => {

  const userId = props.userId

  const getOrderDetails = () => {
    db.collection('users').doc(`${userId}`).collection('orders').get().then((snap) => {
      if(snap){
          const getOrder =  snap.docs.map((doc) => ({
            ...doc.data()
          }))
        console.log(getOrder)
      }
    }).catch(err=>{toast.error(err)}) 
  }

 window.onload = getOrderDetails()

Here userId is a variable. It is used in doc() function as string.

the error happens when you pass a variable into the doc(), which is null, undefined, or a non-string value.

So, first convert the variable to a string by toString()

Then, put the update code inside an if block like this:

if (varName) {
  //update code here
}

this makes sure that the update part only runs if the variable's value is not null or undefined

In my case I just forgot to pass a string value as the second argument of the collection function. I am using it in a reusable custom hook where collectionName is the argument to be used as the collection name, and when I called the hook I forgot to pass an argument.

Hook:

export const useCollection = (collectionName) => {
  let ref = collection(db, collectionName)
  ...
}

Hook Call:

  const { documents: books } = useCollection("books")
Related