【发布时间】:2021-01-10 05:04:36
【问题描述】:
我正在尝试使用这种方法为 Firestore 构建动态查询:Cloud Firestore - Dynamic Querying
这是我构建查询的方式:
buildQueryRef(ref: firebase.firestore.CollectionReference, queryMap: ProductQueryMap, lastDoc?: Item) {
var query : Query = ref;
if (queryMap.minPrice)
query = query.where("price", ">=", queryMap.minPrice) || ref.where("price", ">=", queryMap.minPrice);
if (queryMap.maxPrice)
query = query.where("price", "<=", queryMap.maxPrice) || ref.where("price", "<=", queryMap.maxPrice);
if (queryMap.type)
query = query.where("type", "==", queryMap.type) || ref.where("type", "==", queryMap.type);
if (queryMap.orType)
query = query.where("type", "in", queryMap.type) || ref.where("type", "in", queryMap.type);
if (queryMap.status)
query = query.where("status", "in", queryMap.status) || ref.where("status", "in", queryMap.status);
if (queryMap.keywords || queryMap.orKeywords)
query = query.where("keywords", "array-contains-any", queryMap.keywords) || ref.where("keywords", "array-contains-any", queryMap.keywords);
if (queryMap.userId) {
query = query.where("userId", "==", queryMap.userId) || ref.where("userId", "==", queryMap.userId);
// query.orderBy("userId", "desc");
// orderArr.push("userId");
}
if (queryMap.minPrice || queryMap.maxPrice)
query = query.orderBy("price", "asc") || ref.orderBy("price", "asc");
query = query.orderBy("created", "desc") || ref.orderBy("created", "desc");
if (lastDoc)
query = query.startAfter(lastDoc.created) || ref.startAfter(lastDoc.created);
query = query.limit(12) || ref.limit(12);
return query;
}
因此,例如,如果我进行一个没有参数的查询,它只会设置 orderBy("created", "desc") 和 limit(12) 并且会正常工作,但只要它收到任何其他参数,如 userId 或 type 它不返回任何文档。
起初有一条错误消息,其中包含在 Firestore 中创建复合索引的链接,但后来我按照建议创建了索引,然后它没有返回任何文档。
我想知道是否可以使用这种方法进行查询,因为为每个可能的参数组合编写查询是不切实际的。
提前致谢。
【问题讨论】:
-
这不是必需的:
query = query.where("price", ">=", queryMap.minPrice) || ref.where("price", ">=", queryMap.minPrice);。相反,您可以只做query = query.where("price", ">=", queryMap.minPrice);。
标签: angular typescript google-cloud-firestore angularfire2