繁体   English   中英

FirebaseError:无法使用空路径调用 Function CollectionReference.doc()

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

我从用户集合中获取 id 列表,然后当我尝试从另一个集合中获取 id 数据时出现此错误:

FirebaseError:无法使用空路径调用 Function CollectionReference.doc()

<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}

控制台错误

更新:

问题出在<Room {camera}/>组件中。 Room组件的子组件具有未定义的 Firestore 引用。

错误信息告诉你这段代码有问题:

doc(String(id))

如果id已经是一个字符串(我们无法从您在此处显示的内容中看出),则直接传递它:

doc(id)

如果它是一个数字,并且您想将其转换为字符串:

doc(id.toString())

如果是其他内容,那么您必须更具体地说明您希望如何将其转换为您希望 Firestore 使用的文档 ID 的字符串。

当我尝试从 Firebase 获取特定 ID 的数据时,我在 Next JS 中遇到了相同类型的问题。

如果你在下一个 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;

当您将变量传递给 doc() 时会发生错误,该变量是 null、未定义或非字符串值。

因此,首先通过 toString() 将变量转换为字符串

然后,将更新代码放入 if 块中,如下所示:

 if (varName) { //update code here }

这确保更新部分仅在变量的值不是 null 或未定义时运行

就我而言,我只是忘记传递一个字符串值作为collection function 的第二个参数。 我在一个可重用的自定义钩子中使用它,其中collectionName是用作集合名称的参数,当我调用该钩子时,我忘记传递一个参数。

钩:

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

挂钩呼叫:

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

问题是 doc() function 只接受字符串值。 所以,如果你想在字符串中使用变量,你应该用 $ 符号将变量放入 Backtick 引号中。 像这样:

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

这里 userId 是一个变量。 它在 doc() function 中用作字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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