Getting a Cloud Firestore document reference from a documentSnapshot
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
Jason Berryman
I'm a Google Developers Expert (for Firebase & Google Cloud Platform) and Google Cloud Professional Cloud Architect, specialising in Cloud Firestore data modelling and building backend processes using Google Cloud serverless technologies. My previous company were a launch partner for Cloud Firestore and Cloud Text-to-Speech. We develop telecommunications solutions, which use the power of Google Cloud Platform for the core control and reporting services, built to provide the next generation telephone system, using WebRTC, Asterisk, Drachtio, RTPEngine and Progressive Web Apps. You'll find me at various Google events, such as Google I/O, Cloud NEXT, TADSummit and Firebase Dev Summit, as well as many UK GDG events, where I deliver talks on Cloud Firestore and building microservices on GCP, amongst other things.
Updated on June 12, 2022Comments
-
Jason Berryman about 2 years
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 ofdocumentSnapshot.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 usedocumentSnapshot.id
The documentation for the
path
property is hereMy 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