0

In Firestore when I am writing the query and executing like this , it is working fine

_query = query(collectionTestingRef, 
     where('name','==', 'him') , 
     limit(4));

But when I am taking the query in some variable and then using (required because I need to run a loop and add unknown where condition), it is not working.

var _localWherequery = "where('name','==', 'him')" ; 
_query = query(collectionTestingRef, 
    _localWherequery, 
    limit(4));

How can I achieve this dynamism, knowing that I don't know number of where clauses and I want to use query cursors only in Firestore.

user16217248
  • 3,119
  • 19
  • 19
  • 37
Mohit H
  • 927
  • 3
  • 11
  • 26

1 Answers1

0

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

Rohit Kharche
  • 2,541
  • 1
  • 2
  • 13