Angularfire2 AngularFirestoreCollection not sending keys with each object in collection

spetz83 Source

I'm trying to use Angularfire2 in an Angular 4 app. I am able to get a collection of objects from my firestore using the AngularFirestoreCollection. However, when I iterate through the documents in the collection I have noticed that the documents do not contain the document key. So, I don't think I have any way to do stuff like delete a document from the list in the UI since I don't know the key associated with the document. Here is my code:

  export class CategoryComponent implements OnInit {
      private categoryCollection: AngularFirestoreCollection<any>;
      public categories: Observable<any[]>;
      public category: Category;

      constructor(public db: AngularFirestore, private router: Router) {
          this.categoryCollection = db.collection<any>('categories');
          this.categories = this.categoryCollection.valueChanges();
          this.category = new Category();
      } 
 }

That code gets me a collection that looks like this:

{name: 'Some name'}

Where I would expect something more like:

{key: 'theKey', name: 'Some name'}

I keep looking at the docs on github, but I am either blind, or the docs don't show what I am doing wrong. Maybe I am just ignorant as to how firebase sends documents back in a collection?

javascriptangularfirebasegoogle-cloud-firestore

Answers

answered 1 year ago Isigiel #1

The .valueChanges() method will only give you the data. If you need the key as well you could use .snapshotChanges() and

.map((actions: any) => {
    return actions.map(action => {
      const data = action.payload.doc.data();
      const key = action.payload.doc.id;
      return {key, ...data};
    });
  });

In order to add the document key as well
In your context that might look like this

this.categories = this.categoryCollection.snapshotChanges().map((actions: any) => {
  return actions.map(action => {
    const data = action.payload.doc.data();
    const key = action.payload.doc.id;
    return {key, ...data};
  });
});

That should give you the desired data

comments powered by Disqus