How to get one document by ID Angular 4 + Firestore

Viewed 8852

How to make it work okay? I need only one document from base with id.Is it possible to subscribe it? Because it returns me a Observable object:(

Here`s my code.

getByid(id){
  return this.itemscollection.doc('9K6ue-afwwafwaf').valueChanges();
  }
4 Answers

Let's try to convert the observable to promise like this

  async getDocument(docId:string){
    let document = await this.afs.doc(docId).get().toPromise();
    return document.data();
  }

If you also want the id of the document and use an observable instead, do:

this.firestore.collection('collection').doc('someid').snapshotChanges().subscribe(
      res => {
        this.item= { id: res.payload.id, ...res.payload.data() as InterfaceName };
      },
      err => {
        console.debug(err);
      }
    )

First thing first, you should make sure that your id is right. And I assume you used AngularFirestore to connect to Firebase.

   public this.itemsCollection = null;
   public constructor(private af: AngularFirestore) {
     this.itemCollection = this.af.collection('Your-colection-name');
   }

   public getById(docId: string): any {
     return this.itemCollection
                .doc(docId)
                .valueChanges()
                .subscribe(item => {
                  return item; 
                  // If you prefer including itemId back to object
                  // return {...item, id: docId}
                });
   }
Related