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

时间:2018-08-13 02:03:22

标签: firebase google-cloud-firestore angularfire2

我想根据传入的参数使用多个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(....)
}

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

2 个答案:

答案 0 :(得分:3)

以先前查询为基础,请勿重复先前查询:

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

答案 1 :(得分:0)

如果使用其他查询结构,则可以尝试以下方式:

db.collection("subscriptions").where("email", '==', req.body.email,"&&","subscription_type","==","free").get();

OR

db.collection("subscriptions").where("email", '==', req.body.email).where("subscription_type", '==', 'free111').get();