gpt4 book ai didi

javascript - Firebase Firestore : how to query relevant documents and then update each of them

转载 作者:行者123 更新时间:2023-12-02 21:06:37 27 4
gpt4 key购买 nike

我正在 Firebase/firestore 上开发一个 Web 应用,用户可以在其中登录并撰写自己的帖子。数据存储方式如下:

-用户信息存储在collection('user').doc('uid')下。

-有关用户撰写的帖子的信息存储在collection('post').doc('postid')中,并且该文档具有'userinfo'和'uid'字段。 “userinfo”字段包含“uid”文档中存储内容的精确副本,只是以对象格式。

以下是我想要执行的操作:

  1. 当用户更改数据时,更改会反射(reflect)在文档中。

  2. 根据“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!");
})
}

提前非常感谢!

最佳答案

运行此代码时出现什么错误?这对我来说似乎是在正确的轨道上。

尽管如此,这里还是一些处理此类更新的建议:

  • 不要在客户端执行第二部分,而是使用 Firestore 触发器在服务器端执行(在您的情况下在用户集合中创建 onUpdate 触发器):https://firebase.google.com/docs/functions/firestore-events

    • 在客户端执行的问题是,如果用户关闭页面/浏览器或网站在更新过程中离线,您将获得不一致的数据。
  • 获取查询结果后不需要重新创建DocumentReference,返回的文档已经有一个.ref,您可以直接调用.ref.update()。

编辑:如果您想保留原始代码(在客户端更新),则在所有更新结束之前发生的导航问题是因为 ref.update() 返回一个 promise 。

因此,当客户端离开时,更新队列是在数据库上异步执行的。

为了解决这个问题,我将使用 Promise.all() 来等待所有更新完成。

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;});
});

或者使用await语法(我认为这样更容易维护和理解):

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;

关于javascript - Firebase Firestore : how to query relevant documents and then update each of them,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61207289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com