Getting a single AngularFirestoreDocument from a AngularFirestoreCollection query

岁酱吖の 提交于 2021-01-29 10:42:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!