0

I have this problem where my query returns an empty array. I get no error messages and I see no typos in the query. This is a learning project, following Firehip's NextJS course, but the firebase syntax has been updated from the source code to v9. Apart from this change, I see no discrepancies from the course source code, so I believe the issue lies on Firebase side.

Code:

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

index.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>
    );
}

Terminal output:

posts in users page []

The same query made in firestore interface: firestore query screen

2
  • can you check this stackoverflow link1 & link2 Commented Dec 21, 2022 at 8:19
  • @SathiAiswarya I don't see any applicability to my case. Thank you for trying though. Commented Dec 21, 2022 at 19:28

1 Answer 1

0

Solved it eventually. The problem was on the firestore side, as expected.

I had wrong data layout. I had a posts collection, in which the posts were created by hand. However, the query in the file was for userID/posts collection, so it returned empty.

I learned something about firestore in the process, so there's that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.