首页 > 解决方案 > 使用 Firestore 管理多个 where 条件

问题描述

我正在collection使用3 个搜索字段获取结果。

如果this.tag是空的,我不希望它.where("tagarray", "array-contains", this.tag)工作,同样如果this.dt是空的.where('lastActivityDate', '>=', this.dt)也不应该工作。对this.leadstage.

我该如何处理这种情况?

  loadItems(){
    this.firestore.collection('leads' , ref => ref 
.where("tagarray", "array-contains", this.tag) 
.where('lastActivityDate', '>=', this.dt) 
.where("leadstage" , "==" , this.leadstage) 

编辑 1

我这个函数的全部代码

loadItems(){
this.firestore.collection('leads' , ref => ref 
.where("tagarray", "array-contains", "tag1") //tag success
.where('lastActivityDate', '>=', '07-APR-2020') //date success
.where("leadstage" , "==" , 'Prospect') // leadstage success, this is case sensitive
.limit(5)
).snapshotChanges()
.subscribe(response => {
if(!response.length){
  console.log("no data available");
  return false;
}
this.tableData = [];
for(let item of response){
  var data = Object.assign(item.payload.doc.data(), {id : item.payload.doc.id})
  this.tableData.push(data);

...

编辑 2

错误截图

在此处输入图像描述

编辑 3

当前代码

    this.firestore.collection('leads' , (ref) => {
      let query = ref;
      if (this.tag) {
        query = query.where("tagarray", "array-contains", this.tag) 
      }
      if (this.dt) {
        query = query.where('lastActivityDate', '>=', this.dt) 
      }
      if (this.leadstage) {
        query = query.where("leadstage" , "==" , this.leadstage) 
      }
      return query; 
    }
    )
    .limit(5)
.snapshotChanges()
.subscribe(response => {
if(!response.length){
  console.log("no data available");
  return false;
}
...

错误:

“Query”类型缺少“CollectionReference”类型的以下属性:id、parent、path、doc、addts(2739)

类型“AngularFirestoreCollection”.ts(2339) 上不存在属性“限制”

标签: angulartypescriptfirebasegoogle-cloud-firestoreangularfire2

解决方案


您可以使用多个条件检查来构建查询,如下所示:

this.firestore.collection('leads' , (ref) => {
  let query = ref;
  if (this.tag) {
    query = query.where("tagarray", "array-contains", this.tag) 
  }
  if (this.dt) {
    query = query.where('lastActivityDate', '>=', this.dt) 
  }
  if (this.leadstage) {
    query = query.where("leadstage" , "==" , this.leadstage) 
  }
  return query; 
})...

推荐阅读