Javascript Firebase firestore:如何查询相关文档,然后更新每个文档
我正在Firebase/firestore上开发一个web应用程序,用户可以在其中登录并撰写自己的帖子。数据以以下方式存储: -用户信息存储在集合('User').doc('uid')下 -关于用户写的帖子的信息存储在collection('post').doc('posted')中,文档有'userinfo'和'uid'字段。“userinfo”字段包含存储在“uid”文档中的内容的精确副本,仅为对象格式 以下是我要执行的操作:Javascript Firebase firestore:如何查询相关文档,然后更新每个文档,javascript,firebase,google-cloud-firestore,Javascript,Firebase,Google Cloud Firestore,我正在Firebase/firestore上开发一个web应用程序,用户可以在其中登录并撰写自己的帖子。数据以以下方式存储: -用户信息存储在集合('User').doc('uid')下 -关于用户写的帖子的信息存储在collection('post').doc('posted')中,文档有'userinfo'和'uid'字段。“userinfo”字段包含存储在“uid”文档中的内容的精确副本,仅为对象格式 以下是我要执行的操作: 当用户更改数据时,更改将反映在文档中 查找用户根据“uid”数据
const update = () => {
//This part is for updating user information. This works without any problem.
firebase.firestore().collection('user').doc(user.uid).update({
username: username1,
nickname: nickname1,
intro: intro1
})
.then(()=>{
//This part is for updating all of the document that the user has written based on 'uid' value. This doesn't work.
//Below code is probably way off, but it shows where I am going and what I am trying to do.
firebase.firestore().collection('post').where('uid','==',user.uid).get()
.then((querysnapshot)=>{
querysnapshot.forEach((doc)=>{
let ref=firebase.firestore().collection('post').doc(doc.id);
ref.update({
userinfo: {nickname:nickname1,username:username1,intro:intro1}
})
})
})
}).then(()=>{
alert("Successfully updated!");
window.location.href='/'+username1;
}).catch((error)=>{
alert("Error!");
})
}
提前多谢 运行此代码时出现了什么错误?这对我来说似乎是对的 但尽管如此,以下是一些处理此类更新的建议:
- 不要在客户端执行第二部分,使用Firestore触发器在服务器端执行(在您的情况下,在用户集合中创建onUpdate触发器):
- 在客户端中做的问题是,如果用户在更新期间关闭页面/浏览器或站点离线,则会有不一致的数据。
- 获取查询结果后,不需要重新创建DocumentReference,返回的文档已经有一个.ref,您可以直接调用.ref.update()
firebase.firestore().collection('post').where('uid','==',user.uid).get()
.then((querysnapshot)=>{
const promises = [];
querysnapshot.forEach((doc)=>{
promises.push(doc.ref.update({
userinfo: {nickname:nickname1,username:username1,intro:intro1}
});
});
Promise.all(promises).then(()=>{window.location.href='/'+username1;});
});
或者使用wait语法(我认为更容易维护和理解):
嗨,你说得很对。代码实际上是有效的。问题是该函数将在操作完成之前加载到新页面。例如,按照您的建议将其移动到后端。谢谢现在我明白了!我编辑了答案来解决你原来的问题。
const querysnapshot = await firebase.firestore().collection('post').where('uid','==',user.uid).get();
const promises = [];
querysnapshot.forEach((doc)=>{
promises.push(doc.ref.update({
userinfo: {nickname:nickname1,username:username1,intro:intro1}
});
});
await Promise.all(promises);
window.location.href='/'+username1;