Skip to content

Query documents in firestore from an array of ID’s

I was wondering how I can query documents from a firestore collection from an array of ID’s? I only want the documents in the collection that are in the array of ID’s. I looked at another answer and think my approach is correct, however, I am getting an error.

(node:15105) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'data' of undefined
>      at /Users/username/SideProjects/projectname/functions/index.js:40:38
>      at processTicksAndRejections (internal/process/task_queues.js:95:5)

The error happens because the function is not finding any documents in the collection from that array of ID’s. However, I double-checked the database and know that there are documents in the collection with ID’s from the array.

const admin = require('firebase-admin')

....

let feedItems = db.collection(feedItemsCollection)

feedItemsList = feedItems.where(admin.firestore.FieldPath.documentId(), 'in', ['HPOorsSnbHpTYwwXxfWw']).get().then(snapshot2 => {
       console.log(admin.firestore.FieldPath.documentId())
       console.log("In feed Items")
       //console.log(feedItemIds)
       console.log(snapshot2[0])

       //error happens on this line because snapshot2[0] returns undefined
       console.log(snapshot2[0].data())
})

Snapshot2[0] returns undefined which I’m assuming means that no data was returned. I think I’m not properly calling documentId(), but don’t know the fix.

Answer

There “maybe” two problems with your code. Follow both points to make sure things are working

  1. Data inside snapshot2 maybe empty

You’ll first have to fix your code to test this theory. You’re not accessing data from snapshot2 correctly. To do it right, one way is this:

// `snapshot2` will have a `docs` property that you can leverage
const snapshot2Data = snapshot2.docs.map((doc) => doc.data());
  1. .documentId() may not be doing what it’s supposed to (as you said)

To test this theory, check if snapshot2Data is empty. Run :

console.log(snapshot2Data); // what do you get ?

If no, it’s not empty and you got data back, then you’re all set. Nothing more to do

If yes, it is empty, then run :

console.log(admin.firestore.FieldPath.documentId()); // what do you get ?

Did you get back a string? If no, then we have another problem. You’ll need to take a closer look at your firebase-admin setup, as well.