简体   繁体   中英

Firestore get path of already queried document

I am trying to get the path of a queried document in Firebase Firestore. This is my code:

const location = await db.doc('/locations/US/regions/IOWA').get()
console.log(location.path)

However location.path returns undefined.

location.id works and returns the id.

I have used this as a resource: https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#path

When you call get() on a DocumentReference , you get back a DocumentSnapshot , which does not have a path property.

You're probably looking for location.ref.path .

I know it is old and answered question, this is how I get the document reference from queried document

d.get()
.then(td=>{
   let taskDep = td.data()
   taskDep.id = td.id
   taskDep.ref = td.ref

})

The API documentation for DocumentSnapshot says that the reference of the document can be found in its reference property. So you will want to use this: doc.reference.

The currently accepted answer appears to be outdated, as a DocumentSnapshot does now store the path.

Every DocumentSnapshot has a DocumentReference found under the ref property ( https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentSnapshot#ref )

In the DocumentSnapshot , you can then find a string representation of the path under the path property` ( https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentReference#path )

In short, you can simply use doc.ref.path to get the path.

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