1

I'm using Angular and Firestore

What I want to do

  • Iterate over a Firestore collection

  • Change the value of a field in each AngularFirestoreDocument within that collection

This is where I grab my minutes collection

export class MinutesComponent {
  minutesArray: AngularFirestoreCollection<any>;
  minutes: Observable<any[]>;

  constructor(private afs: AngularFirestore) {
    this.minutesArray = afs.collection<any>('minutes', ref => ref.orderBy('year', 'desc'));
    this.minutes = this.minutesArray.valueChanges();
    ...
  }
}

In my constructor, this is how I try to update each document

this.minutes.subscribe(minutes => {
  minutes.forEach(minute => {

  ####RETRIEVES INDIVIDUAL DOCUMENT FROM DATABASE 
  const minuteRef = this.afs.doc(`minutes/${minute.id}`);

  if (minute.month === 'January') {
    minuteRef.update({'month': 1 });
  } else if (minute.month === 'jan') {
    minuteRef.update({'month': 1 });
  } else {
    minuteRef.update({'month': 2 });
  }
});

Thoughts? I want to loop through the document collection and update a field value of each document in the collection.

For example, if

document.month = january

I would like to change this to

document.month = 1

Thanks.

1 Answer 1

1

valueChanges() doesn't include the id of your minutes item. If you need access to the id, you should use snapshotChanges()

change this line this.minutes = this.minutesArray.valueChanges();

to

this.minutes = this.minutesArray
    .snapshotChanges()
    .pipe(
        map(actions => actions.map(a => {
            const data = a.payload.doc.data();
            const id = a.payload.doc.id;
            return { id, ...data };
        }))
    );
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Tim. This is much closer. Right now it's throwing this error: ReferenceError: map is not defined. Am I missing something from my imports up top? These are my imports so far. Component, OnInit, AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection, Observable from RXJS observable
Indeed! I am missing import { map } from 'rxjs/operators'

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.