Search code examples
javascriptreactjsdatabasegoogle-cloud-firestore

Why is my Firestore query returning no matches even when there is a clear match?


Database Structure

I have a collection of user's infos and I want to return only documents matching with the user's tag if any. Problem is without a query filter I can get the collection and any document. Once I add a query filter, it doesn't matter the equality checker (==, !=), I use it returns nothing. I'm using ReactJS Firestore SDK Library.

This is my code so far, what am I missing?

///InitFirebase.js
import { getFirestore } from "firebase/firestore";
export const firestore = getFirestore();

///EditProfile/Body.js
import { firestore } from "../../scripts/InitFirebase";
import { query, collection, getDocs, where } from "firebase/firestore";

const handleQuery = async() =\> {

const ref = collection(firestore, "user-info");
const q = query(ref, where("myTag", "==", "hal_top_g"));
const querySnapshot = await getDocs(q);

querySnapshot.forEach((doc) =\> {
console.log(doc.id, " =\> ", doc.data());
});
}


Solution

  • The document you're showing in the screenshot has a single top-level which is an object with the same name as the document ID. That object has a number of nested fields, including "myTag". The filter you're using doesn't work because it's looking for a top level field called myTag, not a nested field.

    It's not clear to me why you created the document like this - the extra nesting of these fields doesn't seem to serve any purpose. Maybe you want to look into re-creating this document so that all of the fields are not nested and instead at the top level.

    But if you want to match the nest myTag field in the document you have now, your query would need to look like this:

    const ref = collection(firestore, "user-info");
    const q = query(ref, where("[xxx].myTag", "==", "hal_top_g"));
    

    where [xxx] should be replaced with the name of the top-level object field.