【问题标题】:Firebase - how to fetch additional data for each document on collectionFirebase - 如何为集合中的每个文档获取额外数据
【发布时间】:2018-10-22 20:45:15
【问题描述】:

我尝试为我的每个消息文档获取用户。我们有:

users
    user_id => user_data
message
    msg_id => { message, user_id }

所以我尝试了(基于that answer):

getUserData(userId) {
  const docRef = this.afs.collection('/users').doc(userId);
  return docRef.ref.get();
}

getMsgs(topicId){
  return this.afs.collection('/topics_msgs/' + topicId + "/comments").snapshotChanges().map(actions => {
    return actions.map(a => {
      const commentData = a.payload.doc.data();
      this.getUserData(commentData.user_id).then(
        user => {
          return {user: user.data(), ...commentData};
        }
      );
    });
  });

}

在组件中:

this.firebaseService.getMsgs(this.id).subscribe( msgs => {
  console.log(msgs);
  this.messages = msgs;
})

但它当然不能工作 - 内部映射不会返回任何超出承诺的内容,因此组件会收到 undefined 的列表。

我对如何处理这个问题有点困惑。先谢谢了。

【问题讨论】:

    标签: angular firebase google-cloud-firestore observable angularfire2


    【解决方案1】:

    使用高阶 observables 将您的数据转换为适合您需要的类型。关于您的问题(据我了解),您可以执行以下操作:

        getUserData(userId): Observable<UserData> {
          const docRef = this.afs.collection('/users').doc(userId);
          return docRef.snapshotChanges().pipe(
              map(action => ({ ref: action.payload.ref, ...action.payload.data()}))
          );
        }
    
        getMsgs(topicId): Observable<CommentData[]>{
          return this.afs.collection('/topics_msgs/' + topicId + "/comments").snapshotChanges().pipe(
            mergeMap(actions => {
              const commentsDataObservableArray: Observable<CommentData>[] = actions.map(a => {
                const commentData = a.payload.doc.data();
                return this.getUserData(commentData.user_id).pipe(
                  map(user => {
                    return {user: user.data(), ...commentData};
                  })
                );
              });
              return combineLatest(commentsDataObservableArray);
            })
          );
        }
    

    【讨论】:

    • 谢谢,我最终使用了类似的解决方案,但我承诺,我会尝试你的解决方案,因为它看起来不错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2021-01-23
    • 2020-01-09
    • 2021-04-24
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    相关资源
    最近更新 更多