在JavaScript中动态地向数据库查询添加属性



我正在编写一个函数来查询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查询可以完成此筛选?我在看文档,但是我的过滤器是用键/值对设置的,可以重复或未定义,似乎没有任何复杂的查询方法可以工作。

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

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();

但是,如果您可以使用较新的模块化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));

你可以从你的条件数组映射到where子句:

const exclusions = [
["Colour", "green"],
["Colour", "blue"],
["Greeting", "hello"],
]
let collectionRef = db.collection("database");
const conditions = exclusions.map((e) => where(e[0], "!=", e[1]));
let query = query(collectRef, conditions);
const querySnapshot = await getDocs(query);

最新更新