firebase - 使用 .where() 更新 Firebase 数组。但是,得到错误“.update 不是一个函数
问题描述
因此,我正在尝试更新我的 firebase 中具有数组的文档。
目前,用户文档可能如下所示。
用户名:John postedProjects:['project-one','project-two']
但是,当约翰将“项目三”提交给另一个集合时,我想获取 johns 文档,并将“项目三”添加到他的数组中。
这是我目前的代码(请注意,我没有使用文档 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")
})
})
})}}
解决方案
where()返回一个没有方法的Queryupdate()
对象,正如您从链接的 API 文档中看到的那样。由于无法保证执行查询会产生多少文档,因此您必须get()查询,然后迭代结果以找到与文档匹配的DocumentSnapshot,使用其ref属性为其获取DocumentReference,最后update()
使用该 DocumentReference 的文档。
推荐阅读
- selenium - 使用 Selenium 循环浏览房屋列表
- reactjs - 反应路由器 this.props.history.push ,推送位置但不渲染组件
- python - 减少python中y轴点之间的空间
- bash - 如何执行用BASE64编码的sas程序?
- performance - 优化 rust N primes 生成器
- javascript - 摆脱类型:any in 方法
- python - 调试嵌入式 Python
- python - Python 执行速度慢
- javascript - 如何使用不同的 jest.config.js 进行单元和组件测试?
- c++ - 如何在 QFileDialog 中过滤带有空格字符的文件名?