简体   繁体   English

Cloud FireStore:使用查询检索1个文档

[英]Cloud FireStore: Retrieve 1 document with query

I'm trying to retrieve a single document from a collection. 我正在尝试从集合中检索单个文档。 I'm now using the code below that returns a collections of items, but I know that there is only one item. 我现在使用下面的代码返回一组项目,但是我知道只有一个项目。 So it ain't that clean. 所以不是那么干净。

Setup: 设定:

private db: AngularFirestore
private itemSubs: Subscription[] = [];
itemAd= new Subject<Item>();

fetchItemFromDatabase(itemId: string) {
    this.itemSubs.push(
      this.db.collection('items', id => id.where('itemId', '==', itemId)).valueChanges().subscribe((items: Item[]) => {
        this.itemAd.next(items);
      }));
  }

I tried to do it with this.db.collection('items').doc(itemId).get() , but I'm getting an error on get() that it's not found/supported. 我试图用this.db.collection('items').doc(itemId).get()做到这this.db.collection('items').doc(itemId).get() ,但是我在get()上遇到了一个错误,即找不到/不支持它。 I also didn't got autocompletion when trying to call this methode (methode found in the official cloud firestore documents). 尝试调用此方法时,我也没有自动补全(在官方的Cloud Firestore文档中找到了该方法)。

I looked at around at some other solutions and then tried it with this.db.collection('items').doc(itemId).ref.get().then(...) , but here I got an empty doc back. 我查看了其他解决方案,然后使用this.db.collection('items').doc(itemId).ref.get().then(...)进行了尝试,但是在这里我得到了一个空文档。

So I'm a bit stuck at the moment and I don't want to use that whole collections logic when I know there is only 1 item in it. 因此,目前我有些困惑,当我知道其中只有一项时,我不想使用整个集合逻辑。

There may be multiple documents with itemId equal to a given value. 可能有多个文档的itemId等于给定值。 While you may know that there is only one in your app, the database and API cannot know nor enforce that. 尽管您可能知道应用程序中只有一个,但数据库和API无法知道或强制执行该操作。 For that reason the query you run will always return a query snapshot that potentially contains multiple documents. 因此,您运行的查询将始终返回可能包含多个文档的查询快照。

this.db.collection('items', id => id.where('itemId', '==', itemId))

If you want to enforce that there is only one document with the given item ID, consider using that item ID as the document name instead of storing it as a field in the document. 如果要强制只有一个具有给定项目ID的文档,请考虑使用该项目ID作为文档名称,而不是将其作为字段存储在文档中。

There can be only one document with a given name, so that means the ID is guaranteed to be unique. 具有给定名称的文档只能是一个,因此这意味着该ID被保证是唯一的。 And you can then retrieve that document with: 然后,您可以使用以下方法检索该文档:

this.db.collection('items').doc(itemId)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM