【问题标题】:How to join multiple documents in a Firestore?如何在 Firestore 中加入多个文档?
【发布时间】:2020-11-23 03:43:23
【问题描述】:

我有一个具有以下结构的 Firestore 数据库:

  • 用户

    • [uid]
      • 名称:“用户一”
  • 艺术家

    • [uid]
      • 风格:“流行音乐”
      • user_uid:[uid]

在我的服务中,我有

constructor(private afu: AngularFireAuth, private afs: AngularFirestore, private storage: AngularFireStorage) { 
   this.usersCollection = afs.collection<User>('users');
   this.users = this.usersCollection.valueChanges();
}

getUsers() {
   return this.users = this.usersCollection.snapshotChanges()
     .pipe(map(changes => {
       return changes.map(action => {
         const data = action.payload.doc.data() as User;
         return data
       });
     }));
 }

用户和艺术家之间如何加入?

【问题讨论】:

  • Firestore 不提供任何类似 SQL 的连接查询。您必须查询一个集合,然后迭代结果并分别从另一个集合中获取每个匹配的文档。

标签: javascript firebase ionic-framework google-cloud-firestore angularfire2


【解决方案1】:

使用combineLatest 是一个好方法。由于用户上不存在 user_uid,我将 idField 作为 user_uid 添加到用户。请先查看代码,然后阅读下面的说明。

    import { Component, OnInit } from '@angular/core';
    import { AngularFirestore } from '@angular/fire/firestore';
    import { Observable, combineLatest } from 'rxjs';
    interface User {
      name: string;
      user_uid: string;
    }
    interface Artist {
      style: string;
      user_uid: string;
    }
    interface Joined {
      user_uid: string;
      name: string;
      style: string;
    }
    @Component({
      selector: 'test',
      templateUrl: './test.component.html',
      styleUrls: ['./test.component.scss']
    })
    export class TestComponent implements OnInit {
    
      users$: Observable<User[]>;
      artists$: Observable<Artist[]>;
      joined$: Observable<Joined[]>;
      
      constructor(private afs: AngularFirestore){}
    
      ngOnInit(){
        this.users$ = this.afs.collection<User>('users').valueChanges({idField: 'user_uid'});
        this.artists$ = this.afs.collection<Artist>('artists').valueChanges();
        this.joined$ = combineLatest(this.users$, this.artists$, (users, artists) => {
            const joinedAsMap: Map<string, Joined> = new Map(artists.map(oneArtist =>  [oneArtist.user_uid, { ...{name: null} , ...oneArtist}]));
            users.forEach(one => joinedAsMap.set(one.user_uid , {...{name: one.name}, ...joinedAsMap.get(one.user_uid) } ));
            const joined: Joined[] = Array.from(joinedAsMap.values());
            return joined;
        });
      }
    }
  1. 制作连接界面
  2. 获取两个 observables
  3. 使用最新的组合
  4. 构建一个以 uid 为键、艺术家为值的地图。将名称设置为 null 以便类型可以正常工作。使用扩展运算符合并一些对象。
  5. 遍历用户并将用户信息添加到每个键的值中
  6. 根据地图值构建连接数组
  7. 返回值

你可以用不同的方式来做这件事,但使用 es6 地图是简化某些事情的好方法。此外,没有机会使用真实数据库进行测试,因此您可能需要进行验证。此外,这一切都在用于演示的组件中。您肯定可以在服务中执行此操作。

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2018-06-18
    相关资源
    最近更新 更多