Dominik
Dominik

Reputation: 153

Angular cannot get document id

i'm trying to get the document id of my collection's documents. To do so i created this:

  this.afs.collection("Blogs").valueChanges().map(document => {
    return document.where('title','==','test')(a => {
      const data = a.payload.doc.data();//Here is your content
      const id = a.payload.doc.id;//Here is the key of your document
      console.log('documentsId', id)

    });
  });
}

unfortunately it doesnt work but i dont receive an error as well.

Upvotes: 0

Views: 177

Answers (2)

AVJT82
AVJT82

Reputation: 73357

You are using piece of code that only works for snapshotChanges. valueChanges only returns the object data if no id provided. Giving id as parameter should work in the latest version of angularfire according to the documentation.

But for your case it wouldn't work, you don't know the id I assume. So like the documentation suggests, if you need metadata, use snapShotChanges Also I would assume you are using rxjs version with pipeble operators, if so, use pipe. Also your code looks a bit off with the ref. Try:

import { map } from 'rxjs/operators';

// ....

return this.afs.collection('Blogs', ref => ref.where('title','==','test'))
  .snapshotChanges()
  .pipe(
    map(docs => docs.map(a => {
       const data = a.payload.doc.data(); // Here is your content
       const id = a.payload.doc.id; // Here is the key of your document
       console.log('documentsId', id);
       return {id: id, ...data }
     })
    )
  )

And remember to subscribe to this function in the component.

Upvotes: 2

Ethan Vu
Ethan Vu

Reputation: 2987

The valueChanges() function is going to return an observable, to get a value from an Observable you must subscribe to it:

this.afs.collection("Blogs").valueChanges().subsricbe(val => {
  console.log(value);
  // and do your stuffs
})

Upvotes: 0

Related Questions