Firestore Getting documents id from collection

后端 未结 9 1143
陌清茗
陌清茗 2020-11-30 00:16

I\'m trying to retrieve my documents with id but can\'t figure it out.
Currently I retrieve my documents like this :

const racesCollection: AngularFir         


        
相关标签:
9条回答
  • 2020-11-30 01:10

    To obtain the id of the documents in a collection, you must use snapshotChanges()

        this.shirtCollection = afs.collection<Shirt>('shirts');
        // .snapshotChanges() returns a DocumentChangeAction[], which contains
        // a lot of information about "what happened" with each change. If you want to
        // get the data and the id use the map operator.
        this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
          return actions.map(a => {
            const data = a.payload.doc.data() as Shirt;
            const id = a.payload.doc.id;
            return { id, ...data };
          });
        });
    

    Documentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example

    0 讨论(0)
  • 2020-11-30 01:10

    I've finally found the solution. Victor was close with the doc data.

    const racesCollection: AngularFirestoreCollection<Race>;
    return racesCollection.snapshotChanges().map(actions => {       
      return actions.map(a => {
        const data = a.payload.doc.data() as Race;
        data.id = a.payload.doc.id;
        return data;
      });
    });
    

    ValueChanges() doesn't include metadata, therefor we must use SnapshotChanges() when we require the document id and then map it properly as stated here https://github.com/angular/angularfire2/blob/master/docs/firestore/collections.md

    0 讨论(0)
  • 2020-11-30 01:11

    doc.id gets the UID.

    Combine with the rest of the data for one object like so:

    Object.assign({ uid: doc.id }, doc.data())

    0 讨论(0)
提交回复
热议问题