Angular Firebase Firestore get document ID

孤者浪人 提交于 2019-12-24 19:36:35

问题


My Firebase Firestore database is like this:

Collection:orders
    DocumentID: (autogenerated)
         Document: orderName: string

Variables declared like this:

    orderCollection: AngularFirestoreCollection<Order>
    orders: Observable<Order[]>

I am getting all 'orders' like this:

orderCollection = this.afs.collection('orders');
orders = this.orderCollection.valueChanges();

I am then printing the orders like this:

<tr *ngFor="let o of orders | async">
    <td>{{o.orderName}}</td>
    <td><a (click)="editOrder(o.$key)">Edit</a></td>
</tr>

I everything is working perfect up to the edit part.

For edit: how to I send back the document ID of the order? I want to send the order document ID back so I can then edit it. With the realtime database you could do something with $key, but not with the firestore. Suggestions?


回答1:


In AngularFirestore it is simply document.id. But for this to work you must use snapshotChanges instead of valueChanges. So:

orders = this.orderCollection.snapshotChanges();

And then:

<tr *ngFor="let o of orders | async">
    <td>{{o.data().orderName}}</td>
    <td><a (click)="editOrder(o.id)">Edit</a></td>
</tr>

Inspired by: Firestore Getting documents id from collection and Get Collections with Document Ids Included.




回答2:


Import this

import { map } from 'rxjs/operators';

and in your interface make sure contain id

export interface Order{
  id?:string
  foo1?: string
  foo2?: string
  foo3?: string
}

and your function look like this

this.orderCollection = this.afs.collection<Order>('orders');
 this.orders = this.orderCollection.snapshotChanges().pipe(
      map(kazi => {
      return kazi.map(a => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;

          return { id, ...data };
      });
      })
  );

get result

  this.orders.forEach(order =>{
      console.log(order)   
})

I hope that will help



来源:https://stackoverflow.com/questions/51470538/angular-firebase-firestore-get-document-id

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