首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据Firestore中的id更新单个文档

根据Firestore中的id更新单个文档
EN

Stack Overflow用户
提问于 2020-02-01 22:04:39
回答 1查看 1.4K关注 0票数 0

如何根据id更新firestore中的单个文档?

我想根据它的id更新一个“公告”,但我不知道如何实现这一点。

我在想,是否可以将文档的id传递给editFunction,然后根据传递的id更新文档。

下面是我检索数据的代码:

代码语言:javascript
运行
复制
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的数据:

代码语言:javascript
运行
复制
_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>

并呈现

代码语言:javascript
运行
复制
render () {
  return (
    <View>
    <ScrollView>
      <FlatList data={this.state.content} renderItem={this._renderAnnouncement} keyExtractor={item => item.id} />
    </ScrollView> 
    </View>
  )}

这是我的应用程序的图像

image1

EN

回答 1

Stack Overflow用户

发布于 2020-02-02 00:29:15

当您知道文档的ID时,documentation很清楚如何更新文档:

代码语言:javascript
运行
复制
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()

在您的示例中,要在公告中构建对文档的引用,请执行以下操作:

代码语言:javascript
运行
复制
const id = "..."
const ref = firebase.firestore().collection('announcement').doc(id)

您必须提供该ID。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60017608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档