【问题标题】:Append data from firestore to an array in javascript将数据从firestore附加到javascript中的数组
【发布时间】:2020-02-25 15:58:08
【问题描述】:

我现在正在玩 firebase,我想从数据库中获取显示帖子。 我有一个对象数组,但我不知道如何将数据放入数组中。 这是我的代码:

import * as firebase from "firebase/app";
import db from "@/plugins/firebase";
export default {
  data() {
    return {
      posts: []
    };
  },
  methods: {
    get() {
      db.collection("posts")
        .get()
        .then(snapshot => {
          snapshot.forEach(doc => {
            this.posts = doc.data();
            console.log(this.posts);
          });
        })
        .catch(err => {
          console.log("Error getting documents", err);
        });
    }
  }
};

【问题讨论】:

  • 你分享的代码有什么问题?
  • 我认为你不需要forEach snapshot.data() 应该是一个对象数组

标签: javascript firebase vue.js google-cloud-firestore


【解决方案1】:

想通了,原来我必须创建一个新对象,然后使用扩展运算符。

这是工作代码:

    get() {
      db.collection("posts")
        .get()
        .then(snapshot => {
          let items;
          snapshot.forEach(doc => {
            this.posts.push({
              ...doc.data()
            });
          });
        })
        .catch(err => {
          console.log("Error getting documents", err);
        });
    }

【讨论】:

    【解决方案2】:

    如果@shaykoo 正确理解了您的问题,那么您必须使用push() 方法的反应变体,如下所示:

    .then(snapshot => {
              snapshot.forEach((doc,i)=> {
                this.$set(this.posts, i, doc.data());
              });
    

    【讨论】:

    • 控制台有错误吗? console.log(snapshot.data()) 输出是什么?
    【解决方案3】:

    尝试使用

    .then(snapshot => {
              snapshot.forEach(doc => {
                this.posts.push(doc.data());
              });
    

    您只需要使用 push() 方法,这样来自 Firebase 的数据就会进入上面定义的数组。

    【讨论】:

    • 我试过这个,但是 this.posts 现在是一个观察者。当我遍历帖子时,它确实显示正确的帖子数量,但不显示数据,如帖子标题等。console.log(this.posts) 返回 this -> imgur.com/a/pNnl0eN
    • 也许使用 map() 操作符将数据转换为 JSON 对象,然后使用 subcsribe() 方法可以轻松显示对象数据。
    • 我使用了JSON.stringify(doc.data()) 如果我尝试使用.map(),它会说snapsot.map() 不是函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多