简体   繁体   中英

How to get document ID firestore angular?

I would like to update a field in a document in firestore. However, the document ID is required and all my document ID is auto generated. I have a field called certName which is unique, and how can I get the document ID by matching the certName field? I have tried the code below but it shows the following error.

  updateDb(FILE_NAME,UPDATE_FIELD){
      const ref = this.afs.collection('history', ref => 
      ref.where('certName', '==', FILE_NAME));
      ref.snapshotChanges().pipe(
       map(actions => actions.map(a => {                                                      
         const data = a.payload.doc.data();
         const id = a.payload.doc.id;
         return { id };
  }))).subscribe((_doc: any) => {
   let id = _doc[0].payload.doc.id; //first result of query [0]
   this.afs.doc(`options/${id}`).update({transactionId: UPDATE_FIELD});
  })

Here is the error

ERROR TypeError: Cannot read property 'payload' of undefined
at SafeSubscriber._next (db-service.service.ts:58)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
at SafeSubscriber.next (Subscriber.js:122)
at Subscriber._next (Subscriber.js:72)
at Subscriber.next (Subscriber.js:49)
at MapSubscriber._next (map.js:35)
at MapSubscriber.next (Subscriber.js:49)
at Notification.observe (Notification.js:20)
at AsyncAction.dispatch (observeOn.js:25)
at angular-fire.js:54
 updateDb(FILE_NAME,UPDATE_FIELD) {
     let docID;
     this.afs.collection('history', ref => ref.where('certName', '==', FILE_NAME)).valueChanges().subscribe(res => docID = res.id); 
     // (res.id) - id is the document id, the document id should be stored in the collection as a seperate field
     this.afs.collection('options').doc(docID).update({transactionId: UPDATE_FIELD});
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM