【发布时间】:2020-07-27 03:46:22
【问题描述】:
我正在 Firebase/firestore 上开发一个网络应用,用户可以在其中登录并撰写自己的帖子。数据存储方式如下:
-用户信息存储在collection('user').doc('uid')下。
-关于用户撰写的帖子的信息存储在collection('post').doc('postid') 中,并且该文档具有'userinfo' 和'uid' 字段。 'userinfo' 字段包含存储在 'uid' doc 中的内容的精确副本,只是对象格式。
以下是我想做的操作:
当用户更改数据时,更改会反映在文档中。
根据“uid”数据查找用户写过的所有帖子,然后更新这些数据中的用户信息。
最后一部分对我来说很棘手。 Firebase 文档涵盖了引用几乎是静态的情况,即您知道写入/更新的确切路径。我要做的是寻找一组不一定是静态的文档,然后更新它们。
这是我为此工作编写的代码。第一部分工作没有任何问题。当然,第二部分不起作用。 :) 做第二部分的代码是什么?
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!");
})
}
提前非常感谢!
【问题讨论】:
标签: javascript firebase google-cloud-firestore