user15465547
user15465547

Reputation:

How to perform "where" query using document ID in Cloud Firestore

The is my code :

let newTems = {}
let IDs = ['xyz', 'abc']
let temRef = await db.collection("templates")

For each id in IDs, I am checking if the id is equal to the documentID of any document in the "templates" collection and mapping name along with id to the newTems.

IDs.forEach((id, i) => {
  let temSnap = temRef.where(admin.firestore.FieldPath.documentId(), '==', id).get()
  
  temSnap.forEach(doc => {
    let temData = doc.data()
    
    newTems[i] = {
      id: temData.doc.id,
      name: temData.name,
    }
  })
})

I am getting an error saying

TypeError: temSnap.forEach is not a function

I have tried looking for any syntactical errors but could not find any. Why is this happening?

Thanks for your help.

Upvotes: 0

Views: 75

Answers (1)

Tarik Huber
Tarik Huber

Reputation: 7418

You have two issues here. The first one is that you call the get() without awaiting it for the tempSnap and because that is a async call you can't use it in a forEach because forEach doesn't support async.

To resolve your problem you would need first to loop trough the IDs with a for loop because that iterator supports async calls. And as second use the await on the get() call.

Your code would look like this:

let newTems = {}
let IDs = ['xyz', 'abc']
let temRef = await db.collection("templates")

for (let i = 0; i < IDs.length; i++) {
  const id = IDs[i];
  let temSnap = await temRef
    .where(admin.firestore.FieldPath.documentId(), "==", id)
    .get();

  temSnap.forEach((doc) => {
    let temData = doc.data();

    newTems[i] = {
      id: temData.doc.id,
      name: temData.name,
    };
  });
}

Upvotes: 1

Related Questions