简体   繁体   English

Firestore:如何更新文档的特定字段?

[英]Firestore: How to update specific field of document?

How do I access and update a specific field in angular firestore: 如何访问和更新角度Firestore中的特定字段: 在此处输入图片说明

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

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 首先,请确保您创建的查询名称或ID或什至两者都必须是唯一的
  • Then you subscribe to this query with snapshotChanges 然后,您使用snapshotChanges订阅此查询
  • Next you will get the id from the queried objects 接下来,您将从查询的对象中获取ID
  • After this you use this id to update the doc with the new value 之后,您可以使用此ID使用新值更新文档

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

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 声明要更改的集合(.doc)以指定要更新的文档的ID非常简单(.collection),而in(.update)只需将要更改的更新字段放在其中即可。

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

If your id is unique, only return one query result, I found there is no need to pipe - map . 如果您的ID是唯一的,则仅返回一个查询结果,我发现无需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});
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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