【问题标题】:How to create an Array inside firestore?如何在firestore中创建一个数组?
【发布时间】:2019-01-15 01:13:20
【问题描述】:

Firebase Firestore中创建数组需要哪些代码?

我要存储userDetails

  userName: this.userProfile.name,
  userImage: this.userProfile.image,
  userId: this.userProfile.userId

作为Firestore内的数组

Vue组件:

...
data () {
 return {
     postDetails: {
      createdOn: new Date(),
      content: '',
      userId: null,
      image: null,
      comments: 0,
      likes: 0,
      userDetails: []
    }
    userData: [
     { userName: this.userProfile.name },
     { userImage: this.userProfile.image},
     { userId: this.userProfile.userId }
 }
},
methods: {
  createPost () {
    fb.postsCollection.add({
      createdOn: this.postDetails.createdOn,
      content: this.postDetails.content,
      userId: this.currentUser.uid,
      image: this.postDetails.image,
      comments: this.postDetails.comments,
      likes: this.postDetails.likes
      userData: this.userData
    }).then(ref => {
      this.post.content = ''
      this.$router.push('/dashboard')
    }).catch(err => {
      console.log(err)
    })
  }
}

【问题讨论】:

  • 您的文档中已经有两个数组:tags 和 userData。我根本不清楚你遇到了什么问题。
  • 是的,但我在 firebase 控制台中手动添加了两者
  • 我不知道如何用代码做到这一点
  • 您是否尝试过将一个包含一些数据的 JavaScript 数组实际放入您的代码中?
  • 是的,但在 Firestore 中,它的输出就像普通字符串一样

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


【解决方案1】:

我看到您正在改编此 Firestore 和 Vue.js 教程中的代码:https://savvyapps.com/blog/definitive-guide-building-web-app-vuejs-firebase

实际上在本教程中 userProfile 数据来自 vue-store

  computed: {
    ...mapState(['userProfile', 'currentUser', 'posts'])
  },

您的问题中缺少这部分代码,但这很可能是您的问题的原因:在您的 Vue.js 组件中,您尝试在数据中使用计算属性,但这不可能“因为组件创建时间:数据评估之前计算属性”。

Use computed property in data in Vuejshttps://forum.vuejs.org/t/computed-properties-in-data/11231

只需按如下方式直接访问计算属性即可:userData 将存储为数组。

methods: {
  createPost () {
    fb.postsCollection.add({
      createdOn: this.postDetails.createdOn,
      content: this.postDetails.content,
      userId: this.currentUser.uid,
      image: this.postDetails.image,
      comments: this.postDetails.comments,
      likes: this.postDetails.likes
      userData: [
        { userName: this.userProfile.name },
        { userImage: this.userProfile.image},
        { userId: this.userProfile.userId }
      ]
    }).then(ref => {
      this.post.content = ''
      this.$router.push('/dashboard')
    }).catch(err => {
      console.log(err)
    })
  }
}

【讨论】:

  • 谢谢,但为什么这不起作用:´ userData: [ { userName: this.userProfile.name, userImage: this.userProfile.image, userId: this.currentUser.userId } ]´
  • 我想要索引 0 中的所有 3 个
  • 根据您在教程中所处的位置,userImagename 的值可能未定义。只尝试userId: this.currentUser.userId
  • 我发现了错误,它不适用于`currentUser´,只能用于userProfile
  • 那么一切都好吗?
猜你喜欢
  • 2022-01-12
  • 1970-01-01
  • 2013-12-16
  • 2012-10-22
  • 2012-05-29
  • 2012-07-25
  • 2011-07-03
  • 2015-10-08
  • 2015-12-31
相关资源
最近更新 更多