首页 > 解决方案 > FirebaseError:无法使用空路径调用函数 CollectionReference.doc()

问题描述

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

FirebaseError:无法使用空路径调用函数 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 引用。

标签: javascriptgoogle-cloud-firestoresvelte-3

解决方案


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

doc(String(id))

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

doc(id)

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

doc(id.toString())

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


推荐阅读