Home > Back-end >  Can't access data() in QueryDocumentSnapshot
Can't access data() in QueryDocumentSnapshot

Time:07-21

I'm trying to get data from a document:

await db.collection("collectionName").doc(uid).get("root").data()

but I get: 'data is not a function', which is strange, if I remove data()

await db.collection("collectionName").doc(uid).get("root")

I get the following object, and in fact I can see the root field in _fieldsProto

QueryDocumentSnapshot {
  _fieldsProto: { root: { mapValue: [Object], valueType: 'mapValue' } },
  _ref: DocumentReference {
    _firestore: Firestore {
      _settings: [Object],
.......

anyone knows how I could get fields from QueryDocumentSnapshot?

edit:

I realised I was calling data() before awaiting. The working code is:

const snapshot await db.collection("collectionName").doc(uid).get()
console.log(snapshot.data())

CodePudding user response:

I suggest starting with the documentation to learn how to get a document from Firestore. get() returns a promise which becomes fulfilled when the query is complete.

db.collection("collectionName").doc(uid).get().then(doc => {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch((error) => {
    console.log("Error getting document:", error);
});

As far as I can tell, you aren't using then or await to wait for the query to complete and get a hold of the snapshot in the callback. That isn't an optional step - the query results are not available immediately.

Also, get() does not take any arguments. If you want a field out of the snapshot, you have to dig into the snapshot provided by the callback. If your document field is called "root", then just access it like any object property:

console.log(doc.data().root)
  • Related