You can’t just wrap where
clause conditions within strings in the _localWherequery
variable. Because Firestore will be unable to interpret it as a query filter.
Instead, you can create a function that takes a list of where clauses and builds a Firestore query dynamically.
This is just a example you can modify at your will:
import { collection, getDocs, limit, query, where } from "firebase/firestore";
import { db } from "./config/firebase.js";
const ref = collection(db, "users");
const whereClause = where("name", "==", "him");
const queryLimits = limit(2);
const q = query(ref, whereClause, queryLimits);
const snaps = await getDocs(q);
snaps.docs.forEach(doc => console.log(doc.id, " --> ", doc.data()));
Although you can also use some different methods to create custom queries, One of the methods mentioned is below. Make note that doing in below way will lose all the inference as method arguments will became of type any
:
import { collection, getDocs, query, where } from "firebase/firestore";
import { db } from "./config/firebase.js";
function buildQuery(collectionRef, whereClauses) {
let q = query(
collectionRef,
...whereClauses.map((clause) =>
where(clause.field, clause.operator, clause.value)
)
);
return q;
}
const ref = collection(db, "users");
const whereClauses = [
{ field: "name", operator: "==", value: "him" },
{ field: "age", operator: ">=", value: 18 },
{ field: "gender", operator: "==", value: "male" },
];
const q = buildQuery(ref, whereClauses);
const snaps = await getDocs(q);
snaps.docs.forEach((doc) => console.log(doc.id, " --> ", doc.data()));
Reference: Perform simple and compound queries in Cloud Firestore