带有空字符串、'any' 或 'all' 的 Firestore 查询

IT技术 javascript reactjs firebase google-cloud-firestore
2021-04-25 05:59:47

我的网站上有过滤器,我需要根据过滤器中的输入检索数据。过滤器的某些字段可以为空(''),我希望能够基本上忽略与这些字段相关的那些查询。像这样的东西

//fields
const { country, age, gender, contract, budget_low, budget_high } = queries;

//query
db.collection("users")
        .where("country", "in", country === "" ? "any" : "Nigeria")
        .where("gender", "in", gender === "" ? "any" : "Male")
        .where("age", "in", age === "" ? "any" : "21")
        .get()
        .then((querySnapshot) => {
          var data = [];
          querySnapshot.forEach((doc) => {
            data.push(doc.data());
          });
          setPeers(data);
        })
        .catch((error) => {
          console.log("Error getting documents: ", error);
        });

如果字段为空 (''),有没有办法使用“any”或“all”,这样我就有条件地检索所有数据(如果过滤器字段存在)?

1个回答

您需要动态创建查询,并且只为用户实际选择的值添加条件。

let query = db.collection("users");

if (country !== "") query = query.where("country", "==", country);
if (gender !== "") query = query.where("gender", "==", gender);
if (age !== "") query = query.where("age", "==", age);

query.get()...

在新的module化/v9 语法中,这将是:

let conditions = []

if (country !== "") conditions.push(where("country", "==", country));
if (gender !== "") conditions.push(where("gender", "==", gender));
if (age !== "") conditions.push(where("age", "==", age));

let query = query(collection(db, "users"), ...conditions);

getDocuments(query)...