gpt4 book ai didi

firebase - 基于参数的具有多个 where 子句的 Firestore 查询

转载 作者:行者123 更新时间:2023-12-04 01:53:42 24 4
gpt4 key购买 nike

我想根据传入的参数查询具有多个 where 子句的 Firestore 数据库。以下代码块有效:

getProducts2(accountId: string, manufacturer?: string, materialType?: string): Promise<Product[]> {
return new Promise<Product[]>((resolve, reject) => {
const productCollection2: AngularFirestoreCollection<FreightRule> = this.afs.collection('products');

const query = productCollection2.ref
.where('materialType', '==', materialType)
.where('manufacturer', '==', manufacturer);

query.get().then(querySnapshot => {
if (querySnapshot.size > 0) {
const data = querySnapshot.docs.map(documentSnapshot => {
return documentSnapshot.data();
}) as Product[];
resolve(data);
} //todo else...
});
});
}

但我真正想做的是有条件地包含基于可选参数的 where 子句。以下是我想要的,但它不起作用:
getProducts2(accountId: string, manufacturer?: string, materialType?: string): Promise<Product[]> {
return new Promise<Product[]>((resolve, reject) => {
const productCollection2: AngularFirestoreCollection<FreightRule> = this.afs.collection('products');

const query = productCollection2.ref;
if (manufacturer) {
query.where('manufacturer', '==', manufacturer);
}
if (materialType) {
query.where('materialType', '==', materialType);
}

query.get().then(querySnapshot => {
if (querySnapshot.size > 0) {
const data = querySnapshot.docs.map(documentSnapshot => {
return documentSnapshot.data();
}) as Product[];
resolve(data);
} //todo else...
});
});
}

虽然有效,但此代码仅返回所有没有过滤的产品。

有没有办法构造它,以便我可以根据可选参数进行过滤?

编辑:我意识到我可以做类似的事情:
let query;
if (manufacturer && materialType) {
query = productCollection2.ref.where(....).where(....)
} else if (manufacturer) {
query = productCollection2.ref.where(....)
} else if (materialType) {
query = productCollection2.ref.where(....)
}

我只是希望有一些更优雅的东西。

最佳答案

建立在先前的查询之上,不要重复先前的查询:

let query = collection  // initial query, no filters
if (condition1) {
// add a filter for condition1
query = query.where(...)
}
if (condition2) {
// add a filter for condition2
query = query.where(...)
}
// etc

关于firebase - 基于参数的具有多个 where 子句的 Firestore 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51814343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com