Firestore Getting documents id from collection

136,883

Solution 1

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

Solution 2

For angular 8 and Firebase 6 you can use the option id field

      getAllDocs() {
           const ref = this.db.collection('items');
           return ref.valueChanges({idField: 'customIdName'});
      }

this adds the Id of the document on the object with a specified key (customIdName)

Solution 3

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

Solution 4

For angular6+

    this.shirtCollection = afs.collection<Shirt>('shirts');
    this.shirts = this.shirtCollection.snapshotChanges().pipe(
        map(actions => {
        return actions.map(a => {
            const data = a.payload.doc.data() as Shirt;
            const id = a.payload.doc.id;
            return { id, ...data };
        });
        })
    );

Solution 5

doc.id gets the UID.

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

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

Share:
136,883
DominikG
Author by

DominikG

Updated on July 05, 2022

Comments

  • DominikG
    DominikG almost 2 years

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

    const racesCollection: AngularFirestoreCollection<Races> = this.afs.collection('races');
    return racesCollection.valueChanges();
    

    I do get my documents list perfectly, however there is no doc id with them.

    How can I retrieve it for each document ?

  • Luis Ruiz Figueroa
    Luis Ruiz Figueroa over 6 years
    As I understand your question, do you want to get the id after saving? or do you want to get the id of each document in the collection?
  • Pini Cheyni
    Pini Cheyni about 6 years
    Will this method ensure a unique ID and prevent ID collision ?
  • Diego Venâncio
    Diego Venâncio about 6 years
    Exactly. @Pini Cheyni
  • flobacca
    flobacca about 6 years
    I've been trying for a while to get my code to compile. My question is this.shirts is an Observable<ShirtId[]>. The example returns '{id, ...data}', which is not an object of type ShirtId. How is it being converted to a ShirtId type, it is just an object.
  • cgatian
    cgatian over 5 years
    Works. Changed it to the following to clean it up a bit ``` this.items = db.collection('games').snapshotChanges().pipe( map(actions => actions.map(a => { return { gameId: a.payload.doc.id, ...a.payload.doc.data() }; })) ); ```
  • Lambasoft
    Lambasoft over 5 years
    Hey thanks for your answer, I was having the same problem. I just have one more question, do documents data are fetched as well? I mean performance wise if I just want the ids without fetching the document data, should I use this solution?
  • Luis Ruiz Figueroa
    Luis Ruiz Figueroa over 5 years
    @Lambasoft yes with const data = a.payload.doc.data () as Shirt; the object is being recovered
  • Lambasoft
    Lambasoft over 5 years
    @LuisRuizFigueroa Thanks for your reply! So if I don't call doc.data() the object wont be recovered and I can use it's id normall
  • Sasha Davydenko
    Sasha Davydenko over 5 years
    This! And it's documented for DocumentSnaphot interface (in a collection it really is QueryDocumentSnaphot that extends DocumentSnaphot)
  • KhoPhi
    KhoPhi over 5 years
    This seems like an interesting approach, however, the link doesn't offer any use example, and this answer is, let's not self-sustaining enough
  • Cooper Scott
    Cooper Scott about 5 years
    With newer RXJS, you'll need to write snapshotChanges().pipe(map(actions => ... Hope that helps everyone looking at this post from the future :)
  • Jonathan
    Jonathan about 4 years
    Note: This works on a collection reference, but not a document reference...
  • O-9
    O-9 almost 4 years
    I can get all the data and id, but that spread thing does not work. Is it because i have arrays in my (doc data) object?
  • Savas Karaduman
    Savas Karaduman about 3 years
    simple and nice