【问题标题】:How to perform "where" query using document ID in Cloud Firestore如何在 Cloud Firestore 中使用文档 ID 执行“位置”查询
【发布时间】:2021-05-04 20:09:55
【问题描述】:

这是我的代码:

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

对于IDs 中的每个id,我正在检查id 是否等于“模板”集合中任何文档的documentID,并将nameid 一起映射到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,
    }
  })
})

我收到一个错误提示

TypeError: temSnap.forEach is not a function

我已尝试查找任何语法错误,但找不到任何语法错误。为什么会这样?

感谢您的帮助。

【问题讨论】:

    标签: javascript database firebase google-cloud-firestore


    【解决方案1】:

    这里有两个问题。第一个是你调用get()而不等待tempSnap,因为这是一个async调用,你不能在forEach中使用它,因为forEach不支持async .

    要解决您的问题,您首先需要使用 for loop 循环遍历 ID,因为该迭代器支持 async 调用。第二次使用await 调用get()

    您的代码如下所示:

    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,
        };
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-04
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      相关资源
      最近更新 更多