首页 > 解决方案 > 设置后如何取回文件,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

不知道为什么它不起作用。

有什么帮助吗?

标签: javascriptfirebasereact-nativegoogle-cloud-firestore

解决方案


如 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 */)

推荐阅读