0

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.

André Kool
  • 4,880
  • 12
  • 34
  • 44
Brian A Bird
  • 378
  • 2
  • 18

1 Answers1

1

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
  );
James Daniels
  • 6,883
  • 4
  • 24
  • 28