对 Firestore 文档的 Angular Firestore 查询

Md.*_*lam 5 angularfire2 angular google-cloud-firestore

我有以下查询

    selectedUser$: AngularFirestoreDocument<any>;
    this.selectedUser$ = this.userCollection.ref.where('uid', '==', key)
Run Code Online (Sandbox Code Playgroud)

投掷错误

类型“查询”不可分配给类型“AngularFirestoreDocument”。“查询”类型中缺少属性“ref”。

我试过

this.selectedUser$ = this.userCollection.ref.where('uid', '==', key).get()
Run Code Online (Sandbox Code Playgroud)

没有成功

基本上,我希望查询返回 firestore 文档

Tim*_*ens 14

你得到的错误是因为你混合了 firebase 原生 api 和 angularfire。

selectedUser$: AngularFirestoreDocument<any>;
Run Code Online (Sandbox Code Playgroud)

调用.refAngularFirestoreCollection将其转换为类型firebase.firestore.CollectionReference

话虽如此,有两种可能性可以解决您的问题:

使用angularfire

我假设你userCollection看起来是这样的:this.afs.collection<User>。由于您正在查询一个集合,因此无法确保您的查询谓词uid == key在 firebase 中是唯一的。所以你查询集合和limit()结果。这将返回一个包含一个文档的数组。flatMap()将返回给您一个用户。

this.afs.collection<User>('users', ref => ref.where('uid', '==', key).limit(1))
   .valueChanges()
   .pipe(
       flatMap(users=> users)
   );
Run Code Online (Sandbox Code Playgroud)

使用firebase原生api:

const query = this.usersCollection.ref.where('uid', '==', key);
query.get().then(querySnapshot => {
    if (querySnapshot.empty) {
        console.log('no data found');
    } else if (querySnapshot.size > 1) {
        console.log('no unique data');
    } else {
        querySnapshot.forEach(documentSnapshot => {
            this.selectedUser$ = this.afs.doc(documentSnapshot.ref);
            // this.afs.doc(documentSnapshot.ref).valueChanges().subscribe(console.log);
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

这样,.where如果需要,链接多个子句会更容易一些


Oyv*_*tie -4

如果您添加有关 Firestore 集合和打字稿文件结构的更多详细信息,将会更容易为您提供帮助。

但是,要查询集合,我执行以下操作:

  1. 在构造函数中定义一个私有的 AngularFirestore。

    constructor(
      private afStore: AngularFirestore,
    ) 
    {
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 定义查询并将结果传递给 AngularFirestoreDocument。

    this.selectedUser$ = this.afStore
        .collection('TheNameOfYourCollection').doc<any>(key);
    
    Run Code Online (Sandbox Code Playgroud)