【问题标题】:Update Firebase Array using.where(). But, getting error ".update isn't a function使用 .where() 更新 Firebase 数组。但是,得到错误“.update 不是一个函数
【发布时间】:2020-05-04 12:16:57
【问题描述】:

所以,我正在尝试更新我的 firebase 中包含数组的文档。

目前,用户文档可能如下所示。

用户名:约翰 已发布项目:['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")
        })
      })
    })}}

【问题讨论】:

  • Firestore 不支持更新查询,您可以在其中向服务器发送查询和更新语句。相反,您必须执行查询,检索结果,然后单独更新它们。

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


【解决方案1】:

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

【讨论】:

  • 我将我的代码更新为我认为可行的,但我仍然错过了一些东西或不明白“update()”需要去哪里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2018-09-09
相关资源
最近更新 更多