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?
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.
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.
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.
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.
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.
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:
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;
In addition to Sony's answer, you can get the document reference as well:
const docRefId = ref.docs[0].ref;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With