问题描述
我正在尝试使用以下方法为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);
if (queryMap.status)
query = query.where("status",queryMap.status) || ref.where("status",queryMap.status);
if (queryMap.keywords || queryMap.orKeywords)
query = query.where("keywords","array-contains-any",queryMap.keywords) || ref.where("keywords",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或类型)均不返回任何文档。
起初,出现一条错误消息,其中包含在Firestore中创建复合索引的链接,但是后来我按照建议创建了索引,然后它没有返回任何文档。
我想知道是否可以使用这种方法进行查询,因为针对每种可能的参数组合编写查询都是不现实的。
谢谢。
解决方法
Firestore要求在成功进行查询之前必须存在索引。如何创建它们取决于您,但这不是可选步骤。如果要应用大量的订购和过滤器组合,则要么必须像以前一样手动创建它们,要么找到某种方式来自动化它们。
您可能会发现对generate a JSON description或deploy with the Firebase CLI的索引中的invoke the REST API directly很有帮助。无论哪种方式,它都不是琐碎的工作。