首页 > 解决方案 > 如何将参数动态添加到 Firestore 查询并映射到对象

问题描述

将数据映射到对象并将其作为 promise/observable 返回,同时能够向查询添加动态/条件参数的推荐方法是什么。

在 getCompanies2 中,我可以动态地将参数添加到查询中,但我无法弄清楚如何将返回的数据映射到我的对象并将其作为 promise/observable 返回。

在 getCompanies 中,一切都按我的意愿工作,但如果我有要添加的动态查询参数,我必须复制代码(如下所示)。

注意: convertDocTimeStampsToDate 只是按照它说的去做。我已将其排除在外以减小代码部分的大小。

getCompanies(searchText: string, useWhereActive: boolean): Observable<Company[]> {
    if (useWhereActive) {
      return this.db.collection('companies', ref => ref
      .orderBy('name').startAt(searchText).endAt(searchText + '\uf8ff')
      .where('active', '==', true)
    )
      .snapshotChanges()
      .pipe(
        map(snaps => convertSnaps<Company>(snaps)),
        first()
      );
    } else {
      return this.db.collection('companies', ref => ref
      .orderBy('name').startAt(searchText).endAt(searchText + '\uf8ff')
    )
      .snapshotChanges()
      .pipe(
        map(snaps => convertSnaps<Company>(snaps)),
        first()
      );
    }
  }
​
getCompanies2(searchText: string, useWhereActive: boolean) {
    let query = this.db.collection('companies').ref
      .orderBy('name').startAt(searchText).endAt(searchText + '\uf8ff');
​
    if (useWhereActive) {
      query.where('active', '==', true);
    }
​
    query.get().then(querySnapshot => {
      const results = this.convertDocuments<Company>(querySnapshot.docs);
      console.log(results);
    });
}


convertDocuments<T>(docs) {
    return <T[]>docs.map(doc => {
      return {
        id: doc.id,
        ...doc.data()
      };
    });
}

export function convertSnaps<T>(snaps) {
  return <T[]>snaps.map(snap => {
    const data = convertDocTimeStampsToDate(snap.payload.doc.data());
    return {
      id: snap.payload.doc.id,
      ...data
    };
  });
}

标签: google-cloud-firestoreangularfire2

解决方案


I got it to work like below, I guess I am still getting my head around promises.

Any better solutions will be accepted though as I am still learning and don't know if this is the best method.

getCompanies2(searchText: string, useWhereActive: boolean) {
    let query = this.db.collection('companies').ref
      .orderBy('name').startAt(searchText).endAt(searchText + '\uf8ff');

    if (useWhereActive) {
      query.where('active', '==', true);
    }

    return query.get().then(querySnapshot => {
      return this.convertDocuments<Company>(querySnapshot.docs);
    });
  }

推荐阅读