Angularfire2 Firestore Update same field in multiple documents

馋奶兔 提交于 2019-12-11 16:04:42

问题


I have a profile table and a jobs table stored on Firebase Firestore. I am creating an Angular 5 web site. To save on network calls i added the users profile name to each job document. (Not sure if firestore has table linking). So when the user updates him name, I also have to update their job documents (not many). I can get a collection of jobs with the right user id. But i cannot figure out how to iterate through the list and update the one field without using an Observable (one time call). Here is what I tried that forced my browser into a continous loop

jobsCollection : AngularFirestoreCollection<Job>;
jobDoc: AngularFirestoreDocument<Job>;

jobs: Observable<Job[]>;
job: Observable<Job>;

update(profile: Profile){
  this.jobsCollection = this.db.collection('jobs', ref => {
    return ref.where('user_id', '==',profile.user_id);
  });

  this.tracksCollection.valueChanges(item => {

    console.log('update this record:', item);

    item.forEach(job=> {
      console.log('This is the job');
      this.jobDoc = this.db.doc(`jobs/${job.id}`);
      job.name= profile.name;
      this.jobDoc.update(job);
    });


  });

}

Any help would be greatly appreciated, thanks PK


回答1:


You need a .subscribe() to get the data from this.jobsCollection and iterate through each and update the doc like

this.jobsCollection.snapshotChanges().map(changes=>{
      return changes.map(a=>{
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;
          return {id, ...data}
      })
    }).subscribe(items=>{
        items.forEach(job=>{
            this.db.doc(`jobs/${job.id}`).update({name:profile.name});
        })
     });

I assume you have a filed called id inside each doc underjobs collection, otherwise you need to use .snapshotChanges() instead of .valueChanges()




回答2:


You can do it like that

this.jobsCollection.get().forEach((item) => {
    return item.docs.map(m => {
        return this.db.doc(`jobs/${m.id}`).update({name:profile.name});
    });
});


来源:https://stackoverflow.com/questions/49084835/angularfire2-firestore-update-same-field-in-multiple-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!