1

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

That did it. I knew it was going to be something small like that. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.