Constantin Beer
Constantin Beer

Reputation: 5835

Firestore - How to get the doc id from FirebaseFirestore.QuerySnapshot?

I'm querying a collection for a specific document and trying to get the document-ID from the result of my query that is from type FirebaseFirestore.QuerySnapshot.

My actual query looks like this (I'm using async/await):

result = await db.collection("chatrooms").where("userA", "==", req.body.userA)
            .where("userB", "==", req.body.userB).limit(1).get();

I tried with:

await result.docs.map(doc => {
            return doc.id
        })

But that gives me an undefined back.

What am I doing wrong?

Upvotes: 5

Views: 6261

Answers (1)

imjared
imjared

Reputation: 20554

A QuerySnapshot contains zero or more DocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach method. The number of documents can be determined via the empty and size properties.

So it's going to return an array (QuerySnapshot) of QueryDocumentSnapshots. You need to loop over the snapshots using forEach() then you can get the document ID from each QueryDocumentSnapshot

https://firebase.google.com/docs/reference/js/firebase.firestore.QueryDocumentSnapshot

If you're using typescript, you should be able to see the definitions, methods, and properties in your IDE.

Upvotes: 7

Related Questions