问题
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.
回答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
);
来源:https://stackoverflow.com/questions/50913325/getting-a-single-angularfirestoredocument-from-a-angularfirestorecollection-quer