【问题标题】:Dynamically adding properties to database query in JavaScript在 JavaScript 中为数据库查询动态添加属性
【发布时间】:2022-07-13 00:45:39
【问题描述】:

我正在编写一个函数来查询仅具有某些属性的文档的 Firestore 数据库集合。过滤器被定义为“键、值”对的数组。 例如:

[
  ["Colour", "green"],
  ["Colour", "blue"],
  ["Greeting", "hello"],
]

这个数组可以是任意长度,我试图获取数据库中没有在过滤器数组中列出的值的每个文档。

我可以这样做:

await db.collection("database")
  .where("Colour", "!=", "blue")
  .where("Colour", "!=", "green")
  .where("Greeting", "!=", "hello").get()

我的问题是过滤器可以是任意长度,所以我不能编写查询来拥有一组.where() 方法。 在 JavaScript 中有什么方法可以动态地向查询中添加方法,如上所示(不知道需要添加多少方法)?

我现在的解决方法是查询整个数据库,然后使用 Javascript 过滤器函数对其进行排序,但我只想查询数据库中所需的值。

或者,是否有任何其他 Firestore 查询可以完成此过滤器?我正在查看docs,但我的过滤器设置为使用可以重复或未定义的键/值对的方式,似乎任何复杂的查询方法都不起作用。

【问题讨论】:

    标签: javascript database firebase google-cloud-firestore nosql


    【解决方案1】:

    假设您正在构建一个仅包含排除键值对的数组,并且您排除的值已正确索引,我们可以开始定义一些常量:

    const collectionRef = db.collection("database");
    
    const excludedKeyValuePairs = [
      ["Colour", "green"],
      ["Colour", "blue"],
      ["Greeting", "hello"],
    ]
    

    现在我们有了这些,我们可以使用 Array#reduce 构建查询。

    const query = excludedKeyValuePairs
      .reduce(
        (query, [key, value]) => query.where(key, "!=", value), // appends the new constraint, returning the new query object
        collectionRef
      );
    
    const querySnapshot = await query.get();
    

    但是,如果您可以使用较新的modular Firestore SDK,您也可以使用以下方法获得相同的结果:

    import { getFirestore, getDocs, collection, query, where } from "firebase/firestore";
    
    const db = getFirestore();
    const collectionRef = collection(db, "database");
    const constraints = [
      where("Colour", "!=", "green"),
      where("Colour", "!=", "blue"),
      where("Greeting", "!=", "Hello")
      // elements can also be added or removed using standard array methods as needed.
    ]
    // OR const constraints = excludedKeyValuePairs.map(([key, value]) => where(key, "!=", value))
    
    const querySnapshot = await getDocs(query(collectionRef, ...constraints));
    

    【讨论】:

      猜你喜欢
      • 2018-12-08
      • 1970-01-01
      • 2012-03-20
      • 2014-05-29
      • 2018-12-19
      • 2020-07-11
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      相关资源
      最近更新 更多