如何根据id更新firestore中的单个文档?
我想根据它的id更新一个“公告”,但我不知道如何实现这一点。
我在想,是否可以将文档的id传递给editFunction,然后根据传递的id更新文档。
下面是我检索数据的代码:
retrieveAnnouncement = () => {
const announcements = [];
const id = []
/* retrieve announcements */
firebase.firestore().collection('announcement').get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
announcements.push(doc.data());
//here is the unique id that I will use later on to update a single document
console.log(doc.id)
});
this.setState({ content: announcements, docID: id });
console.log(announcements)
})
.catch(err => console.log(err));
};
editSingleAnnouncement = () => {
//get the unique id of an announcement and update it.
}在这里,它呈现来自firestore的数据:
_renderAnnouncement = ({ item }) =>
//display the content of announcement
<Card>
<Text h3>{item.TITLE}</Text>
<Text h5>{item.CONTENT}</Text>
<View style={styles.container}>
<Button title="Edit" containerStyle={{marginLeft: 10, width: 80}} />
<Button title="Delete" buttonStyle={{backgroundColor: 'red'}} containerStyle={{marginLeft: 10, width: 80}} />
</View>
</Card>并呈现
render () {
return (
<View>
<ScrollView>
<FlatList data={this.state.content} renderItem={this._renderAnnouncement} keyExtractor={item => item.id} />
</ScrollView>
</View>
)}这是我的应用程序的图像
发布于 2020-02-02 00:29:15
当您知道文档的ID时,documentation很清楚如何更新文档:
var washingtonRef = db.collection("cities").doc("DC");
// Set the "capital" field of the city 'DC'
return washingtonRef.update({
capital: true
})
.then(function() {
console.log("Document successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});您需要构建一个指向要更新的文档的DocumentReference,包括集合的名称和文档ID,然后对其调用update()。
在您的示例中,要在公告中构建对文档的引用,请执行以下操作:
const id = "..."
const ref = firebase.firestore().collection('announcement').doc(id)您必须提供该ID。
https://stackoverflow.com/questions/60017608
复制相似问题