繁体   English   中英

当存在应返回的数据时,Firestore 查询返回空数组

[英]Firestore query returns empty array when there is data that should be returned

我有这个问题,我的查询返回一个空数组。 我没有收到任何错误消息,也没有在查询中看到拼写错误。 这是一个学习项目,跟随Firehip的NextJS课程,但是firebase语法已经从源代码更新到v9。 除了这个变化,我没有看到课程源代码有任何差异,所以我认为问题出在 Firebase 方面。

代码:

helperFunction.tsx:

export async function getUserWithUsername(username: string) {
    const q = query(
        collection(firestore, "users"),
        where("username", "==", username),
        limit(1)
    );
    const userDoc = (await getDocs(q)).docs[0];
    return userDoc;
}

索引.tsx:

export async function getServerSideProps({ query: urlQuery }) {
    const { username } = urlQuery;

    const userDoc = await getUserWithUsername(username);

    let user: object = {};
    let posts: any[] = [];

    if (userDoc) {
        user = userDoc.data();

        const postsQuery = query(
            collection(getFirestore(), userDoc.ref.path, "posts"),
            where("published", "==", true),
            orderBy("createdAt", "desc"),
            limit(5)
        );

        posts = (await getDocs(postsQuery)).docs.map(postToJSON);
        console.log("posts in users page", posts);
    }

    return {
        props: { user, posts },
    };
}

    export default function UserProfilePage({ user, posts }) {
    return (
        <main>
            <h1>User's page</h1>
            <UserProfile user={user} />
            <PostFeed posts={posts} />
        </main>
    );
}

终端输出:

posts in users page []

在 firestore 界面中进行的相同查询: Firestore 查询屏幕

最终解决了它。 正如预期的那样,问题出在 Firestore 方面。

我有错误的数据布局。 我有一个posts集合,其中的帖子是手工创建的。 但是,文件中的查询是针对userID/posts集合的,因此它返回了空。

我在这个过程中学到了一些关于 firestore 的东西,就是这样。

暂无
暂无

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

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