【问题标题】:Node.js Firestore forEach collection query cannot populate associative arrayNode.js Firestore forEach 集合查询无法填充关联数组
【发布时间】:2020-07-17 12:34:37
【问题描述】:

在这个简化的示例中,关联数组 A 无法在 Node.js Firestore 查询中填充——就好像存在范围问题:

var A = {};

A["name"] = "nissa";

firestore.collection("magic: the gathering")
  .get()
  .then(function(query) {
    query.forEach(function(document) {
        A[document.id] = document.id;
        console.log(A);
    });
  })
  .catch(function(error) {
});

console.log(A);

控制台输出:

{ name: 'nissa' } < last console.log()
{ name: 'nissa', formats: 'formats' } < first console.log() (in forEach loop)
{ name: 'nissa', formats: 'formats', releases: 'releases' } < second console.log() (in forEach loop)

感谢任何帮助,如果需要,请要求提供更多详细信息。

【问题讨论】:

    标签: node.js google-cloud-firestore


    【解决方案1】:

    数据是从 Firestore 异步加载的,在这种情况下,您的主代码会继续运行。

    通过放置一些日志语句最容易看出这意味着什么:

    console.log("Starting to load data");
    firestore.collection("magic: the gathering")
      .get()
      .then(function(query) {
        console.log("Got data");
      });
    console.log("After starting to load data");
    

    当你运行这段代码时,它会打印:

    开始加载数据

    开始加载数据后

    得到数据

    这可能不是您期望的日志记录顺序。但它实际上按预期工作,并解释了您看到的输出。到您最后一次运行 console.log(A); 时,数据尚未加载,因此 A 为空。


    解决方案很简单,但通常需要一些时间来适应:所有需要数据库数据的代码都必须在回调中,或者从那里调用。

    所以是这样的:

    var A = {};
    
    A["name"] = "nissa";
    
    firestore.collection("magic: the gathering")
      .get()
      .then(function(query) {
        query.forEach(function(document) {
            A[document.id] = document.id;
        });
        console.log(A);
      })
    

    另见:

    【讨论】:

    • 非常感谢弗兰克。是的,这一切都有点新意。如何将数据“返回”到“回调”之外,或者从那里被调用。一旦查询完成?我肯定需要改变我的思维方式,但我发现的大多数示例只是简单的 console.log() 处理数据后查询的示例(在回调内部)。我无法想象如何构建一个在回调中工作的程序,尤其是当该程序需要来自多个集合的更多查询(因此更多回调)时。再次感谢。
    • 我给你的链接展示了很多在回调之外使用数据的例子,尽管它总是在一些回调中使用。唯一不需要的方法是使用async / await,为此我还提供了一个示例链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2010-11-27
    • 2019-10-02
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    相关资源
    最近更新 更多