云功能:使用“where”查询,无法获取docID Nodejs

a8jjtwal  于 2023-10-17  发布在  Node.js
关注(0)|答案(2)|浏览(121)

我使用“where”查询来获取一个文档,这样我就可以更新它。我需要的文件,这是我正在努力。我在看文件,但进展不大。我使用Firebase云函数,Nodejs和JavaScript。

const admin = require("firebase-admin");
const firestore = admin.firestore();

exports.bucketTesting = functions.https.onRequest(async (req, res) => {

//code to source file.metadata.mediaLink

  const imagesRef = firestore.collection("images");
  const specificImageRef = await imagesRef
    .where("imageUrl", "==", file.metadata.mediaLink)
    .get();
  console.log(specificImageRef);

  specificImageRef.forEach((doc) => {
    console.log(doc.id, "=>", doc.data());
  });
}

console.log(specificImageRef)打印数据(我不能使用),但是forEach中的console.logs不打印任何东西。
我如何获得DocID?

wz8daaqr

wz8daaqr1#

const admin = require("firebase-admin");
const firestore = admin.firestore();

exports.bucketTesting = functions.https.onRequest(async (req, res) => {

  //code to source file.metadata.mediaLink

  const imagesRef = firestore.collection("images");
  
  // the following will return an array 
  const specificImages = (await imagesRef
    .where("imageUrl", "==", file.metadata.mediaLink)
    .get()).docs.map(each => each.data()) || [];
    
    
  /* the console log on the next line will show the array
  it will show multiple items if there is more than one document
  where imageUrl === file.metadata.mediaLink */
  console.log(specificImages);
  
  /* all is left to do is to return the array 
    or return a single document */
    
  // the following is the case when you are just returning a single document
  res.send({
    desiredData: specificImages?.[0] ?? {} // fallback if there is no document
  })
}
irtuqstp

irtuqstp2#

您的意见:“如何获取文档或docID?“

您的代码正确,可以获取文档docID和数据,但如注解中所述,查询返回0个文档。

由于您确定只有一个文档对应于查询,因此您可以做的唯一调整是使用docs数组,如下所示:

exports.bucketTesting = functions.https.onRequest(async (req, res) => {

  const imagesRef = firestore.collection("images");
  const querySnapshot = await imagesRef
          .where("imageUrl", "==", file.metadata.mediaLink)
          .get();

  if (querySnapshot.size === 0) {
     // No document found
     // Send back a message or an error
     res.status(500).send("No document found");
  } else {
     const uniqueDocSnapshot = querySnapshot.docs[0];
     console.log(uniqueDocSnapshot.id, "=>", uniqueDocSnapshot.data());

     res.send(...);
  }

        

})

相关问题