javascript - 设置后如何取回文件,firebase?
问题描述
设置新的文档 ID 后如何取回文档 ID?
我有一些尝试,但这是我最新的:
handleCreateCard = async (name, token) => {
try {
const new_card = await firestore()
.collection('Cards')
.doc()
.set({
user_id: user.uid,
name: name,
token: token,
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.then(() => this.props.navigation.navigate("CardDetail", {cardId: 2}));
// console.log("ATTEMPT !", handleCreateCard);
// console.log("ATTEMPT 2", new_card);
} catch (error) {
console.log(error.toString(error));
}
}
该docRef
行让我得到错误:
错误: TypeError: null is not an object (evaluating 'docRef.id')
记录 handleCreateCard 错误: ReferenceError: Can't find variable: handleCreateCard
然后new_card
:“这在这里未定义”
尝试做:
.then(docRef => {
console.log("Document written with ID: ", this.id); // also tried docRef.id
})
我得到Document written with ID: undefined
了 docRef.id:TypeError: null is not an object (evaluating 'docRef.id')
该文档也在创建中,所以不确定为什么它没有回来
我尝试了几种方法来做到这一点,然后还尝试了上面的所有方法:Firestore - How to get document id after adding a document to a collection
不知道为什么它不起作用。
有什么帮助吗?
解决方案
如 API 文档中所述,不带参数的doc()立即返回已包含 ID的DocumentReference 。
const docRef = await firestore()
.collection('Cards')
.doc()
const id = docRef.id
docRef
.set(...)
.then(/* use the id here if you want */)
推荐阅读
- typescript - Firebase snapshot.ref.parent 可能为“null”
- python - 使用语音识别时我在 python 中遇到语法错误
- java - 无法从 SQLite 数据库填充我的活动 (DrinkActivity)
- javascript - 400 BAD REQUEST POST 使用 Axios 在 React 与 Nodejs/Express 中
- reporting-services - PowerBI 计算列的多个 if 条件
- forms - Grav CMS 与 Recaptcha v3 集成
- laravel - updateOrcreate() 在我更新现有数据时记录新数据
- reactjs - 触发时如何将我的反应语义模态定位在中心
- python - 如何连接具有不同行项目的两个数据框
- visual-studio - 在 javascript 中键入右大括号会自动格式化 K&R 样式的块