Ad

AngularFire2 Query Not Returning Document ID

I'm using AngularFire2 in a service to get data from a Firestore collection. The code looks something like this:

this.db.collection('organizations')
  .valueChanges()
  .pipe(first())
  .toPromise()
  .next(organization => console.log(organization));

The console is logging the organization object exactly as expected. But that object is lacking the id of the Firestore document.

So I'm wondering if there's something that can be done to get the ID as part of that query...

Ad

Answer

you can use the snapshot something like this:

private getOrganizations(whereClause: any): any {
        return this.db.collection('organizations')
            .snapshotChanges()
            .pipe(
                map((docs: any) => {
                    return docs.map(a => {
                        const data = a.payload.doc.data();
                        const id = a.payload.doc.id;
                        return {id, ...data};
                    });
                })
            );
    }

For more details about snapshotChanges check this:

https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md#snapshotchanges

snapshotChanges()

What is it? - Returns an Observable of data as a DocumentChangeAction.

Why would you use it? - When you need the document data but also want to keep around metadata. This metadata provides you the underyling DocumentReference and document id. Having the document's id around makes it easier to use data manipulation methods. This method gives you more horsepower with other Angular integrations such as ngrx, forms, and animations due to the type property. The type property on each DocumentChangeAction is useful for ngrx reducers, form states, and animation states.What is it? - Returns an Observable of data as a

Ad
source: stackoverflow.com
Ad