Firestore: How to update specific field of document?

你离开我真会死。 提交于 2021-01-23 11:08:02

问题


How do I access and update a specific field in angular firestore:


回答1:


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});
    })
}



回答2:


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



回答3:


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);
  });



回答4:


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});
  });
}


来源:https://stackoverflow.com/questions/53184131/firestore-how-to-update-specific-field-of-document

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