Home > database >  Build dynamic where condition firestore
Build dynamic where condition firestore

Time:04-19

The default query method is complicated. I was trying to create a wrapper around it which attaches where clauses based on the fields passed to it.

import { collection, getDocs, getFirestore, query, conditions } from "firebase/firestore";

const db = getFirestore();

export const getDocuments = async ({ collectionName, whereConditions = {}, fetchSingle = false }) => {
  const whereQuery = Object.entries((whereConditions)).map(([key, value]) => where(key, "==", value));
  const q = query(collection(db, collectionName), ...whereQuery)
  const querySnapshot = await getDocs(q);
  const result = [];
  querySnapshot.forEach((doc) => {
    // doc.data() is never undefined for query doc snapshots
    result.push({ id: doc.id, ...doc.data() });
  });
  return fetchSingle ? result[0] : result;
}

But it returns [] array in each case. It seems where() is not being applied.

Update:

When I log queryWhere this is what I get.

[
    {
        "hc": {
            "segments": [
                "id"
            ],
            "offset": 0,
            "len": 1
        },
        "lc": "==",
        "fc": "EQdg5wDPFYCEqhImRznD",
        "type": "where"
    }
]

When I log whereConditions this is what I get,

{
    "id": "EQdg5wDPFYCEqhImRznD"
}

I tried many combination. It is working when I pass other filters than id.

It doesn't return result when id is passed in where.

CodePudding user response:

Currently your query is looking for "id" field in the document. If you want to query based on document ID then try this:

import { documentId } from "firebase/firestore"

const qConstraint = where(documentId(), "==", "DOC_ID")
  • Related