【问题标题】:Update a single document base on id in Firestore根据 Firestore 中的 id 更新单个文档
【发布时间】:2020-02-01 14:04:39
【问题描述】:

如何根据 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>
  )}

这是我的应用程序的图像

image1

【问题讨论】:

  • 您确实需要_renderAnnouncement 函数中每个文档的ID。如果该 ID 不是您的项目的一部分,您可以将其显式传递给函数。有关示例,请参阅此问题/答案:stackoverflow.com/questions/54842905/…

标签: javascript firebase react-native google-cloud-firestore


【解决方案1】:

documentation 清楚地说明了在您知道文档 ID 时如何更新文档:

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-16
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2019-10-23
    • 2018-09-15
    • 2019-01-07
    相关资源
    最近更新 更多