javascript - 如何在 Firebase 中动态更新集合中的文档
问题描述
我已经能够动态创建记录(用户配置文件)并在 Firebase 中检索他们的唯一 ID。
但现在我希望能够让最终用户更新他们的个人资料。虽然我可以检索配置文件的文档 ID aka uid。如何模板化动态获取登录人员的 uid 并更新该特定记录的能力?
我尝试了以下方法:
async updateProfile() {
const docRef = await db.collection("users").get(`${this.userId}`);
docRef.update({
optInTexts: this.form.optInTexts,
phone: this.form.mobile
});
db.collection("users")
.update({
optInTexts: this.form.optInTexts,
phone: this.form.mobile
})
.then(function () {
console.log("Profile successfully updated!");
})
.catch(function (error) {
console.error("Error updating document: ", error);
});
}
`
我也试过
async updateProfile() {
const docRef = await db.collection("users").where("userId", "==", `${this.userId}`);
docRef.update({
optInTexts: this.form.optInTexts,
phone: this.form.mobile
});
db.collection("users")
.update({
optInTexts: this.form.optInTexts,
phone: this.form.mobile
})
.then(function () {
console.log("Profile successfully updated!");
})
.catch(function (error) {
console.error("Error updating document: ", error);
});
}
``
和这个
async updateProfile() {
const docRef = await db.collection("users").get(`${this.userId}`);
docRef.update({
optInTexts: this.form.optInTexts,
phone: this.form.mobile
});
db.collection("users/`${this.userId}`")
.update({
optInTexts: this.form.optInTexts,
phone: this.form.mobile
})
.then(function () {
console.log("Profile successfully updated!");
})
.catch(function (error) {
console.error("Error updating document: ", error);
});
}
错误docRef.update is not a function
解决方案
在查看了这篇文章后,我能够解决这个问题:如何更新单个 firebase firestore 文档。
我试图引用的集合是一个用户表,其中包含从 Firebase 开箱即用的 Google 身份验证创建的数据。因此,查询和更新数据与我的其他数据不同,其中 doc ID 等于集合的 uid。工作解决方案:
async updateProfile() {
const e164 = this.concatenateToE164();
const data = {
optInTexts: this.form.optInTexts,
phone: e164};
const user = await db.collection('users')
.where("uid", "==", this.userId)
.get()
.then(snapshot => {
snapshot.forEach(function(doc) {
db.collection("users").doc(doc.id).update(data);
});
})
}
推荐阅读
- javascript - 使用jQuery动态创建一个在选择图像时调用的函数
- c# - 赋值前匹配的声明
- node.js - 如何使用 express 将集合替换为 PUT?
- python - 在 Ubuntu 16.04 上为 box2d.py 构建轮子失败
- sql - 范围内的日期
- java - Spring Boot 2.0.X 属性异常处理程序响应 ascii?
- batch-file - 跳过“点击‘下载’ - 请等待 5 秒 - 点击‘跳过广告’”
- audio - 使用 Google 应用脚本在 Google 幻灯片上播放音频
- shell - 仅在 shell 脚本中使用 find 命令匹配特定扩展的问题
- python - Python:从一行中获取数字