如何获取Cloud Firestore查询返回的数据?

时间:2019-06-21 16:44:02

标签: javascript firebase google-cloud-firestore

我编写了以下代码来呈现一些帖子(这些帖子存储在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);
  }
};

运行代码时,将获得以下控制台输出: Console output

在函数外部,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);
  }
};

此代码的结果是相同的: enter image description here

为回应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);
  }
};

这仍然会导致相同的问题: enter image description here

1 个答案:

答案 0 :(得分: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