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

问题描述 投票:0回答:2

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

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

javascript firebase google-cloud-firestore angularfire
2个回答
4
投票

基于先前的查询,不要重复先前的查询:

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

0
投票

如果使用不同的查询结构,您可以尝试以下方式:

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

db.collection("subscriptions").where("email", '==', req.body.email).where("subscription_type", '==', 'free111').get();
© www.soinside.com 2019 - 2024. All rights reserved.