从 AngularFirestoreCollection 查询中获取单个 AngularFirestoreDocument [英] Getting a single AngularFirestoreDocument from a AngularFirestoreCollection query

查看:23
本文介绍了从 AngularFirestoreCollection 查询中获取单个 AngularFirestoreDocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Firestore 中,我的 Vendor 文档中有一个 uid 作为字段:

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}`);
}

我想创建一个类似的函数,它也返回一个 AngularFirestoreDocument,但该函数需要一个 uid 来获取文档:

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;
}

似乎我必须查询一个 AngularFirestoreCollection,但不知道如何从集合中提取文档.

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

推荐答案

我建议使用 uid 作为记录的键;这样你就可以通过 URL w/getVendor

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

否则需要查询:

// 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
  );

这篇关于从 AngularFirestoreCollection 查询中获取单个 AngularFirestoreDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆