【问题标题】:How To Add Firebase Firestore Document Auto Generated ID Add In Collection Custom Data Field In React Js [duplicate]如何在 React Js 中添加 Firebase Firestore 文档自动生成的 ID 在集合中添加自定义数据字段 [重复]
【发布时间】:2021-02-21 17:44:44
【问题描述】:

我想在我的项目中喜欢这个示例。查看示例

但是当我通过 react js 实现这个例子时,我不能这样做。查看我的代码:

constructor(props) {
    super(props);

    this.ref = firebase.firestore().collection('stack_over')

    const id = firebase.firestore().collection('stack_over').doc().id

    this.state = {
        question_id: id,
        question_title: '',
    };
}
onSubmitData = (e) => { 
 e.preventDefault() 
 const { question_id, question_title } = this.state; 
 this.ref.add({ question_id, question_title })
 .then((docRef) => { 
 this.setState({ question_id:'', question_title:'' }) }).catch((error) => { console.error("", error) }) }

我想在插入新数据然后自动生成的文档 id 插入 question_id 字段时执行此操作。我该怎么做?

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    这个:

    const id = firebase.firestore().collection('stack_over').doc().id
    

    会给你一个自动生成的id,但是如果你想向数据库中添加数据那么你需要使用set():

    firebase.firestore().collection('stack_over').doc(id).set({
            question_id: id,
            question_title: 'title',
        }).then(function() {
        console.log("Document successfully written!");
       })
        .catch(function(error) {
          console.error("Error writing document: ", error);
       });
    

    https://firebase.google.com/docs/firestore/manage-data/add-data

    【讨论】:

    • onSubmitData = (e) => { e.preventDefault() const { question_id, question_title } = this.state; this.ref.add({ question_id, question_title }).then((docRef) => { this.setState({ question_id:'', question_title:'' }) }) .catch((error) => { console.错误(“”,错误)})}
    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多