但是当我通过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字段时,我想这样做。我该怎么办?
答案 0 :(得分:0)
此:
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