Rogerto
Rogerto

Reputation: 327

Firestore: How to update specific field of document?

How do I access and update a specific field in angular firestore: enter image description here

Upvotes: 5

Views: 22316

Answers (4)

sbrina813
sbrina813

Reputation: 11

If your id is unique, only return one query result, I found there is no need to pipe - map.

updateDoc(_id: string, _value: string) {
  let doc = this.afs.collection('options', ref => ref.where('id', '==', _id));
  doc.snapshotChanges().subscribe((res: any) => {
    let id = res[0].payload.doc.id;
    this.afs.collection('options').doc(id).update({rating: _value});
  });
}

Upvotes: 1

Swoox
Swoox

Reputation: 3750

Ok you have to do the following steps:

  • First make sure that you create a query either on name or ID or even both, it need to be unique
  • Then you subscribe to this query with snapshotChanges
  • Next you will get the id from the queried objects
  • After this you use this id to update the doc with the new value

It would look something like this:

updateDoc(_id: string, _value: string) {
  let doc = this.afs.collection('options', ref => ref.where('id', '==', _id));
  doc.snapshotChanges().pipe(
    map(actions => actions.map(a => {                                                      
      const data = a.payload.doc.data();
      const id = a.payload.doc.id;
      return { id, ...data };
    }))).subscribe((_doc: any) => {
     let id = _doc[0].payload.doc.id; //first result of query [0]
     this.afs.doc(`options/${id}`).update({rating: _value});
    })
}

Upvotes: 2

Sofien Abdeddaim
Sofien Abdeddaim

Reputation: 41

Is very simple (.collection) to declare the collection that u want to change (.doc) to specify the id of the document that u want to update and the in (.update) just put the update field that u want change it

 constructor(private db: AngularFirestore) {}
 this.db
  .collection('options')
  .doc('/' + 'mzx....')
  .update({rating: value})
  .then(() => {
    console.log('done');
  })
  .catch(function(error) {
   console.error('Error writing document: ', error);
  });

Upvotes: 3

Sunil
Sunil

Reputation: 11241

It should be pretty easy task. You can use update function and pass the field name and value to update.

ex :

this.db.doc(`options/${id}`).update({rating:$rating}); //<-- $rating is dynamic

Upvotes: 11

Related Questions