使用.where()更新Firebase阵列。但是,出现错误“ .update不是函数

问题描述 投票:0回答:1

因此,我正在尝试更新Firebase中具有数组的文档。

当前,用户文档可能看起来像这样。

用户名:JohnpostedProjects:['project-one','project-two']

但是,当John将“ project-three”提交给另一个集合时,我想获取johns文档,并将“ project-three”添加到他的数组中。

目前是我的代码(请注意,我没有使用该文档UID,因为我已经将UID设置为名称,但是用户可以更改其用户名下线,但其UID保持不变)

  var newProject = db.collection('users').where('user_id', '==', this.userInfo.user_id);
  newProject.update({
    postedProjects: firebase.firestore.FieldValue.arrayUnion("test")
  })

这是我从Firebase doc开始执行的代码,稍作调整,将.doc(uid)更改为.where,以使现有用户与集合中的用户匹配。

但是,我收到一条错误消息,指出“ newProject.update不是函数”。

-添加了.where但仍然出错,因为我不确定将“ update()”放在哪里

        db.collection('users').where('user_id', '==', this.userInfo.user_id)
      .get()
      .then(function(querySnapshot)  {
        querySnapshot.forEach(function(doc) {

        doc.data().update({
          postedProjects: firebase.firestore.FieldValue.arrayUnion("new project")
        })
      })
    })}}
firebase vue.js google-cloud-firestore
1个回答
1
投票

where()返回一个Query对象,该对象没有update()方法,如从链接的API文档中可以看到的那样。由于无法保证executing a query可以产生多少文档,因此您必须get()查询,然后迭代结果以找到与文档匹配的DocumentSnapshot,使用其ref属性获得DocumentReference ],最后使用该DocumentReference update()该文档。

© www.soinside.com 2019 - 2024. All rights reserved.