【问题标题】:A cleaner way to query a collection and return the data as a list?查询集合并将数据作为列表返回的更简洁的方法?
【发布时间】:2019-01-24 12:34:11
【问题描述】:

似乎有一种更简洁、更优化的方式来查询 Firestore 集合,在每个文档上调用 doc.data(),然后返回一个数组作为结果。将文档推入结果数组的顺序感觉很随意。

这段代码有很多步骤:

  1. 创建了一个新的result 变量
  2. 进行查询以检索“故事”集合
  3. 对于每个文档,我们调用doc.data()
  4. 我们将每个文档推送到 result 数组中
  5. 返回result数组
  function getStories() {
    var result = [];
    db.collection('stories').get().then(querySnapshot => {
        querySnapshot.forEach(doc => result.push(doc.data()));
    })
    return result;
  }

代码运行良好,但似乎我们可以用更少的步骤以更简洁的方式编写此代码。

【问题讨论】:

  • 你能给出一个你想要实现的输入和期望输出的示例数据吗..
  • 恐怕你得到了想要的行为。这应该总是返回空数组

标签: javascript arrays google-cloud-firestore


【解决方案1】:

正如乔治评论的那样,您共享的代码实际上不起作用。由于 Firestore 异步加载数据,因此您始终会在加载数据之前返回数组。所以你的数组是空的。

在代码中:

function getStories() {
  var result = [];
  db.collection('stories').get().then(querySnapshot => {
    querySnapshot.forEach(doc => result.push(doc.data()));
  })
  return result;
}
var result = getStories();
console.log(result.length);

将记录:

0

要解决此问题,您需要返回一个承诺,该承诺会在数据加载后解决。大致如下:

function getStories() {
  var result = [];
  return db.collection('stories').get().then(querySnapshot => {
    querySnapshot.forEach(doc => result.push(doc.data()));
    return result;
  })
}

所以这基本上添加了两个返回语句,这使您的result 冒泡,然后作为来自getStories 的承诺返回。要调用它,你会这样做:

getStories().then(result => {
  console.log(result.length);
})

这将记录正确数量的结果。

【讨论】:

    【解决方案2】:

    首先,定义一个map 函数用于firebase(命名为mapSnapshot,因为它专门用于firebase):

    const mapSnapshot = f => snapshot => {
      const r = [];
      snapshot.forEach(x => { r.push(f(x)); });
      return r;
    }
    

    然后,您可以使用Promise 和mapSnapshot:

    function getStories() {
      return db.collection('stories').
        get().
        then(mapSnapshot(doc => doc.data()));
    }
    

    使用示例:

    getStories().then(docs => ... do whatever with docs ...)
    

    说实话,如果用作一次性解决方案,它并不是更少的代码。但这里的巧妙之处在于,它允许创建可重用的抽象。例如,您可以使用mapSnapshot 创建一个snapshotToArray 函数,只要您需要将DataSnapshot 从firebase 转换为普通的Array,就可以重复使用该函数:

    const snapshotToArray = mapSnapshot(x => x);
    

    请注意:这不依赖于任何集合名称。您可以将它与 any 集合中的 any DataSnapshot 一起使用,以将其转换为 Array!

    这还不是全部。您可以轻松地将 DataSnapshot 的内容创建为包含内容的常规 Array 函数:

    const readDocsData = mapSnapshot(x => x.data());
    

    同样,这看起来没什么大不了 - 直到您意识到,您还可以创建一个 fromFirebase 函数,它允许查询各种数据集:

    const fromFirebase = (name, transform = x => x) => {
      return db.collection(name).get().then(transform);
    }
    

    然后你可以像这样使用它:

    fromFirebase('stories', readDocsData).then(docs => {
      // do what you want to do with docs
    });
    

    这样,最终结果的步骤更少,您作为程序员可以立即注意到。但它产生了(尽管可重用)几个中间步骤,每个步骤都隐藏了一些抽象。

    【讨论】:

    • querySnapshot 没有map 函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多