简体   繁体   中英

How to read Firebase document with auto generated document id using Javascript

I am trying to read a single document from a Firebase collection using a variable that is populated with the document id. The document id is correct and the document exists in the collection. When I initiate the code using variable it seems that the read was successful but there is no data in the field I am interested in. (See Code below).

 db.collection("Pswref").doc(clpdocid).get().then((docRef) => { const SingleRecord = docRef.data(); console.log('yyyyyy - Great document found using fixed id for doc id ', docRef.data()); console.log('yyyyyy - Title from database = >', SingleRecord.title); console.log('yyyyyy - Doc id ', clpdocid); }).catch((error) => { console.error('yyyyyy - Error getting document ', error); });

However when I hard-code the document id in the get statement all is well and I can access the information needed. (See code below).

 db.collection("Pswref").doc("NoA6EBijcgsBIIOZCsWC").get().then((docRef) => { const SingleRecord = docRef.data(); console.log('xxxxxx - Great document found using fixed id for doc id ',docRef.data()); console.log('xxxxxx - Title from database = >', SingleRecord.title); }).catch((error) => { console.error('xxxxxx - Error getting document ', error); });

The image shows the console.log output as per the script. NB: You will note that the above queries are exactly the same accept for the doc id reference used and I get a different result as per the output generated via the console.

在此处输入图像描述

Can someone help me to understand why this might happen and what the solution might be?

I have commented on the line out giving the error and rerun so that the output in the console can show that the clpdocid is actually correctly populated.(see snipped below)and then output on the new image.

 db.collection("Pswref").doc(clpdocid).get().then((docRef) => { const SingleRecord = docRef.data(); console.log('yyyyyy - Great document found using fixed id for doc id ', docRef.data()); //console.log('yyyyyy - Title from database = >', SingleRecord.title); console.log('yyyyyy - Doc id ', clpdocid); }).catch((error) => { console.error('yyyyyy - Error getting document ', error); });

在此处输入图像描述

在此处输入图像描述

It's certainly the case that clpdocid doesn't actually contain the value you expect. The undefined that you're printing from docRer.data() is proof that you've requested a document that doesn't exist, since the API documentation for data() says to expect undefined if the document was not found.

Try logging the value of clpdocid before the query to make sure you have the document ID you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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