firebasegoogle-cloud-firestoreangularfire2angularfire5

Getting a single AngularFirestoreDocument from a AngularFirestoreCollection query


In Firestore, I have a uid as a field in my Vendor documents:

/vendors
    +doc1
        uid: 1
    +doc2
        uid: 2

To access the vendors, I'm using the following function:

getVendor(index: string): AngularFirestoreDocument<Vendor> {
    return afs.doc<Vendor>(`vendors/${index}`);
}

I'd like to create a similar function, which also returns an AngularFirestoreDocument, but the function takes a uid to get the document:

getVendorByUID(uid: string): AngularFirestoreDocument<Vendor> {

    ...

    return theDoc;
}

It seems like I have to query an AngularFirestoreCollection, but don't know how to extract the Document from the Collection.


Solution

  • I'd recommend using the uid as the key for the record; that way you can just reference it by URL w/getVendor

    Otherwise you need to query:

    // Query the first vendor where the uid matches
    afs.collection<Vendor>(`vendors`, ref => ref.where('uid', '==', uid).limit(1))
      .valueChanges()
      .pipe(
        map(vendors => vendors[0]) // flatten the result
      );