Angular Firestore:如何更新文档的特定字段?
如何访问和更新angular firestore中的特定字段:Angular Firestore:如何更新文档的特定字段?,angular,firebase,google-cloud-firestore,Angular,Firebase,Google Cloud Firestore,如何访问和更新angular firestore中的特定字段: 这应该是一项相当简单的任务。您可以使用update函数并传递要更新的字段名和值 例: this.db.doc(`options/${id}`)。更新({rating:$rating})// 好的,您必须执行以下步骤: 首先,确保您创建了一个关于name或ID甚至两者的查询,它需要是唯一的 然后使用快照更改订阅此查询 接下来,您将从查询的对象中获取id 在此之后,使用此id使用新值更新文档 它看起来像这样: updateDoc(_
这应该是一项相当简单的任务。您可以使用update函数并传递要更新的字段名和值 例:
this.db.doc(`options/${id}`)。更新({rating:$rating})// 好的,您必须执行以下步骤:
- 首先,确保您创建了一个关于name或ID甚至两者的查询,它需要是唯一的
- 然后使用快照更改订阅此查询
- 接下来,您将从查询的对象中获取id
- 在此之后,使用此id使用新值更新文档
它看起来像这样:
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});
})
}
声明要更改的集合非常简单(.collection)
(.doc)要指定要更新的文档的id,只需在(.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);
});
如果您的id是唯一的,只返回一个查询结果,我发现没有必要使用管道
-映射
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});
});
}
你是对的,但是它没有解释如何获取id。请编辑你的问题,以显示你尝试了什么,但没有按照你期望的方式工作。
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});
});
}