Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get document id from Firestore after fetching document

How can I get the document id of a firestore document after successfully fetching the document. I am fetching user data from firestore collections like this

const ref = await db.collection('users').where('phone', '==', phone)
            .where('password', '==', password).get();

I have a valid document after executing this query.

const data = ref.docs[0].data();

How can I get the auto generated document id? I tried data.id and data.path, it is returning undefined.

How can I access the auto generated id?

like image 969
Sony Avatar asked Mar 24 '18 20:03

Sony


People also ask

How do I get my ID after adding firestore?

When you call the . add method on a collection, a DocumentReference object is returned. DocumentReference has the id field, so you can get the id after the document was created. // Add a new document with a generated id.

How do I get fetch data from firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.

How do I find the number of documents in a collection firestore?

If you need a count, just use the collection path and prefix it with counters . As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter.

How do I retrieve data stored in Cloud Firestore?

There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.

What happens when I set a listener in Cloud Firestore?

When you set a listener, Cloud Firestore sends your listener an initial snapshot of the data, and then another snapshot each time the document changes. Note: While the code samples cover multiple languages, the text explaining the samples refers to the Web method names.

How to get the ID of an object in angular fire?

AngularFire lets you find the IDs and add them to the objects in 2 different ways. Let’s say you are fetching a regular list of objects from your database using collectionData (): We have 2 ways of getting the ID and adding it to the resulting object, first, we can use the idField parameter:


2 Answers

In my code, it was actually trying to get the data id, instead of document id i got the document id by adding const docRefId = ref.docs[0].id;

like image 180
Sony Avatar answered Oct 13 '22 12:10

Sony


In addition to Sony's answer, you can get the document reference as well:

const docRefId = ref.docs[0].ref;
like image 24
Kai - Kazuya Ito Avatar answered Oct 13 '22 10:10

Kai - Kazuya Ito