繁体   English   中英

在快照 Firestore JS 中返回文档 ID

[英]Return documents ID in snapshot firestore JS

我是 Coding 和 Firestore 的新手,由于某种原因,我无法正确使用。 我想返回doc.id但我得到的输出未定义它似乎没有返回任何数据

console.log(doc.id)的输出是hqyWHGrVHvopdyVACRkn ID输出未定义

const getProductDocId = async (productName1) =>{
  try{
    const ID = await firestore().collection('product').where('productName' ,'==', productName1).get().then(snapshot=>{
      snapshot.docs.every(doc => {
        console.log(doc.id + " THIS is DOC.ID")
        return doc.id
      })
    })
    
    console.log(ID)
 
   }catch(error){
     console.log("Error @ Get Prdocut ID  " + error)
   }finally{
     console.log(ID)
   }
 } 

您以错误的方式申请了await 如果将Promise传递给await表达式,它会等待Promise完成并返回已完成的值。

try {
  const snapshot = await firestore()
    .collection("product")
    .where("productName", "==", productName1)
    .get();
  let id = null;
  snapshot.docs.every((doc) => {
    console.log(doc.id + " THIS is DOC.ID");
    id = doc.id;
  });
  console.log(id);
} catch (error) {
  console.log("Error @ Get Prdocut ID  " + error);
} finally {
  console.log(id);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM