简体   繁体   English

设置后如何取回文件,firebase?

[英]How to get back document after set, firebase?

How can I get back the documument ID after I set a new one?设置新的文档 ID 后如何取回文档 ID?

I have a few attempts but here is my latest:我有一些尝试,但这是我最新的:

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));
        }
    }

The docRef line gets me the error: docRef行给我错误:

Error: TypeError: null is not an object (evaluating 'docRef.id')错误: TypeError: null is not an object (evaluating 'docRef.id')

Logging handleCreateCard Error: ReferenceError: Can't find variable: handleCreateCard记录 handleCreateCard 错误: ReferenceError: Can't find variable: handleCreateCard

Then the new_card : "THIS IS HERE undefined"然后是new_card :“这是未定义的”

Tried doing:尝试做:

.then(docRef => {
    console.log("Document written with ID: ", this.id); // also tried docRef.id
})

I get Document written with ID: undefined with docRef.id: TypeError: null is not an object (evaluating 'docRef.id')我得到Document written with ID: undefined with docRef.id: TypeError: null is not an object (evaluating 'docRef.id')

The document is being created as well so not sure why it's not coming back该文档也在创建中,所以不确定为什么它没有回来

I've tried a handful of ways to do this and then also tried everything in here which some is above: Firestore - How to get document id after adding a document to a collection我尝试了几种方法来做到这一点,然后还尝试了上面的所有方法: Firestore - How to get document id after adding a document to a collection

Not sure why it's not working.不知道为什么它不起作用。

Any help?有什么帮助吗?

As described in the API documentation, doc() with no parameters returns a DocumentReference immediately which already contains the ID.如 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 */)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM