1

我正在尝试检索 firebase 文档,并使用 snapshot.forEach 块获取该文档的关联图像的签名 URL。我将内容和签名的 url 推送到一个数组中,这样我就可以在执行 forEach 块后将整个数组返回到我的角度前端。

我正在使用 firebase admin-sdk 生成存储桶引用 - 'storageRef'。

但是由于某种原因,我在前端收到的新闻列表数组似乎是空的。有人可以让我知道这里出了什么问题吗?

exports.getContents = async(req, res, next) => {

  var newslist = [];
  // Get the contents of each document
  var snapshot = await db.collection('feeds').doc(req.query.language).collection(req.query.type).get();
  snapshot.forEach((doc) => {

      storageRef.file("thumbnail/" + req.query.type + "/" + doc.id + ".png").getSignedUrl({
        action: 'read',
        expires: '12-12-2025'
      }).then(signedUrls => {
        newslist.push({
          author: doc._fieldsProto.author,
          cat: doc._fieldsProto.cat,
          content: doc._fieldsProto.content,
          createdAt: doc._fieldsProto.createdAt,
          excerpt: doc._fieldsProto.excerpt,
          id: doc.id,
          imageSrc: signedUrls[0],
          lastEdit: doc._fieldsProto.lastEdit,
          media: doc._fieldsProto.media,
          os_android: doc._fieldsProto.os_android,
          os_ios: doc._fieldsProto.os_ios,
          region: doc._fieldsProto.region,
          status: doc._fieldsProto.status,
          title: doc._fieldsProto.title,
          type: doc._fieldsProto.type
          });
      }).catch(error => {
        console.log(error);
      });
  });
  res.json({
    message: "Feeds retrieved successfully",
    feeds: newslist
  });
}
4

1 回答 1

0

谢谢@Đăng Khoa Đinh。我用你的逻辑找到了一个可行的解决方案。这是我的代码

const db = admin.firestore(); 
var storageRef = admin.storage().bucket();

exports.getContents = async(req, res, next) => {

  newslist = []; let i = 0;
  // Print the ID and contents of each document
  var snapshot = await db.collection('feeds').doc(req.query.language).collection(req.query.type).get();
  var promiseSet = snapshot.docs.map(item => getSignedUrl(req.query.type,item.id)); 
  var signedUrlsSet = await Promise.all(promiseSet);
  snapshot.forEach((doc) => {
    let signedUrls = signedUrlsSet[i];
    newslist.push({
      author: doc._fieldsProto.author,
      cat: doc._fieldsProto.cat,
      content: doc._fieldsProto.content,
      createdAt: doc._fieldsProto.createdAt,
      excerpt: doc._fieldsProto.excerpt,
      id: doc.id,
      imageSrc: signedUrls[0],
      lastEdit: doc._fieldsProto.lastEdit,
      media: doc._fieldsProto.media,
      os_android: doc._fieldsProto.os_android,
      os_ios: doc._fieldsProto.os_ios,
      region: doc._fieldsProto.region,
      status: doc._fieldsProto.status,
      title: doc._fieldsProto.title,
      type: doc._fieldsProto.type
    });
    i++;
  });
  res.json({
    message: "Feeds retrieved successfully",
    feeds: newslist
  });
 }

这是我的 getSignedUrl 函数

function getSignedUrl(req, doc) {
  return storageRef.file("thumbnail/" + req + "/" + doc + ".png").getSignedUrl({
    action: 'read',
    expires: '12-12-2025'
  });
} 
于 2021-05-11T16:31:54.580 回答