【问题标题】:How to update / push data to an empty array in Firestore - Firebase如何将数据更新/推送到 Firestore 中的空数组 - Firebase
【发布时间】:2019-07-16 09:09:20
【问题描述】:

我正在使用 React 和 Firestore。当用户注册时,我在他们的个人资料中保存了一个空数组{chats : []}。当用户向另一个用户撰写消息时,在此期间我想将一些数据推送到这个 chats 数组。应该记住一件事,这个特定的数组不应该被覆盖。简单地说,应该向它推送一个新值。

我能做的就是

db.collection('Users').doc(userid).update({
  chats: ['somevalue']
})

注意:我的方法会覆盖整个数组的数据。

Firestore 用户数据示例

db.collection('Users').doc(this.state.user.uid).set({
  name: `${this.state.fname} ${this.state.lname}`,
  email: this.state.email,
  time: new Date().getTime(),
  id: this.state.user.uid,
  address: this.state.place,
  username: this.state.username,
  bio: this.state.bio,
  img: this.state.imgURL,
  chats: [] //To add the chats list to the user profile
}).then(() => {
  console.log("User Info Added...");
}).catch(error => {
  console.log(error);
})

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

    我已经想通了,我认为这是实现它的最简单方法。您可以通过 cmets 了解它的工作原理。

    我所做的只是:

    1. Users 对象中获取chats[] 数组
    2. 将新值推送到检索到的数组中
    3. 使用推送给它的新更新值更新 chats[] 数组。

    //Get the Following Users through the specific document ID
    Promise.all([
      db.collection('Users').doc(new Cookies().getCookie('uid')).get(),
      db.collection('Users').doc(this.props.data['0'].userId).get()
    ]).then(e => {
      //Get the Chats array from the object
      let c = e.map(lists => lists.data().chats)
      //push new values which is 'loc' in my case to the Chats arrays
      c.forEach(e => {
        e.push(loc)
      })
    
      //Make two Other promises to update the chat arrays with the upated values.
      Promise.all([
        db.collection('Users').doc(new Cookies().getCookie('uid')).update({
          chats: c[0]
        }),
        db.collection('Users').doc(this.props.data['0'].userId).update({
          chats: c[1]
        }),
      ]).then(e => {
        console.log("Docments Updated")
      })
    
    })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2022-01-10
      • 2021-12-25
      相关资源
      最近更新 更多