Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a Cloud Firestore document reference from a documentSnapshot

The issue

I'm trying to retrieve the document reference from a query. My code returns undefined. I can get the path by extracting various parts of documentSnapshot.ref, but this isn't straightforward.

What I'd like to return is a reference which I can then later use to .update the document, without having to specify the collection and use documentSnapshot.id

The documentation for the path property is here

My code

const db = admin.firestore();  return db.collection('myCollection').get().then(querySnapshot => {   querySnapshot.forEach(documentSnapshot => {     console.log(`documentReference.id   = ${documentSnapshot.id}`);     console.log(`documentReference.path = ${documentSnapshot.path}`);     // console.log(`documentReference.ref = ${JSON.stringify(documentSnapshot.ref)}`);   }); }); 

Output

documentReference.id   = Jez7R1GAHiR9nbjS3CQ6 documentReference.path = undefined documentReference.id   = skMmxxUIFXPyVa7Ic7Yp documentReference.path = undefined 
like image 831
Jason Berryman Avatar asked Feb 22 '18 18:02

Jason Berryman


People also ask

How do I get data from Filesnapshot firestore?

A DocumentSnapshot contains data read from a document in your Cloud Firestore database. The data can be extracted with the getData() or get(String) methods. If the DocumentSnapshot points to a non-existing document, getData() and its corresponding methods will return null .

How do I get data from QueryDocumentSnapshot?

A QueryDocumentSnapshot contains data read from a document in your Cloud Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted using the getData() or the various get() methods in DocumentSnapshot (such as get(String) ).

Which function is used to fetch data from the firebase document?

The Get() function in Go unmarshals the data into a given data structure. Notice that we used the value event type in the example above, which reads the entire contents of a Firebase database reference, even if only one piece of data changed.


1 Answers

In your code, documentSnapshot is an object of type DocumentSnapshot. It looks like you're assuming that it's an object of type DocumentReference. A the purpose of a reference is to locate a document. The purpose of a snapshot is to receive the contents of a document after it's been queried - they're definitely not the same thing. A DocumentSnapshot doesn't have a path property.

If you want the DocumentReference of a document that was fetched in a DocumentSnapshot, you can use the ref in the snapshot. Then you can get a hold of the ref's path property:

documentSnapshot.ref.path 
like image 104
Doug Stevenson Avatar answered Oct 16 '22 21:10

Doug Stevenson