【问题标题】:How do I obtain the data returned by a Cloud Firestore query? [duplicate]如何获取 Cloud Firestore 查询返回的数据? [复制]
【发布时间】:2019-06-21 16:44:02
【问题描述】:

我编写了以下代码来呈现一些帖子(存储在 Cloud Firestore 实例中)。我正在使用 mithril.js。

let SummaryPostView = {
  posts: [],
  view: function () {
    let query = blogModels.postModel.getNLatest(20, "created");
    query.then(function (data) {
      this.posts = data;
      console.log("INSIDE VALUE: ");
      console.log(this.posts);
    });
    console.log("OUTSIDE VALUE: ");
    console.log(this.posts);
  }
};

当我运行我的代码时,我会获得以下控制台输出:

this.posts 的值在函数外与this.posts inside the function. 的值不同由于this 的行为可能令人困惑,我还尝试了以下代码:

let SummaryPostView = {
  posts: [],
  view: function () {
    let query = blogModels.postModel.getNLatest(20, "created");
    var x = [];
    query.then(function (data) {
      x = data;
      console.log("INSIDE VALUE: ");
      console.log(x);
    });
    console.log("OUTSIDE VALUE: ");
    console.log(x);
  }
};

这段代码的结果是一样的:

为了回应 Chris Sandvik 的回答,我也尝试了以下代码

let SummaryPostView = {
  posts: [],
  view: function () {
    let query = blogModels.postModel.getNLatest(20, "created");
    query.then(function (data) {
      this.posts = data.docs.map(function (doc) {
        let out = doc.data();
        out.id = doc.id;
        return out;
      });
      console.log("INSIDE");
      console.log(this.posts)
    });
    console.log("OUTSIDE");
    console.log(this.posts);
  }
};

这仍然会导致同样的问题:

【问题讨论】:

标签: javascript firebase google-cloud-firestore


【解决方案1】:

由于您的输出是 QuerySnapshot,因此您需要像这样访问您的数据:

query.then(function (data) {
  this.posts = data.docs.map(doc => {
    let out = doc.data();
    out.id = doc.id;
    return out;
  });
});

您需要使用 docs 属性访问 QuerySnapshot 中的文档数组,并使用 .data() 方法访问它们的数据。

更多信息在这里:https://firebase.google.com/docs/reference/js/firebase.firestore.QueryDocumentSnapshot.html

【讨论】:

  • 不幸的是,这仍然会导致同样的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 1970-01-01
  • 2020-03-17
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多