gpt4 book ai didi

javascript - firestore 中的查询数组

转载 作者:行者123 更新时间:2023-12-02 23:07:25 29 4
gpt4 key购买 nike

我必须在 firestore 中保存文档,一份是用户文档,一份是推文文档。我正在尝试复制 Twitter 克隆。所以我的用户有关注者数组。我想向用户显示其推文及其关注者推文。用户集合为:

{
name:test,
email:test@gmail.com,
follower:[a@gmail.com,b@gmail.com]
}

推文集合是:

{
text:Dummy tweet,
by:test@gmail.com,
img:dummyImageSource
}

我无法弄清楚。如果我使用 test@gmail.com 登录,并且我有一个关注者(假设是 a@gmail.com)。我需要如何查询来获取我的评论(test@gmail.com)和所有关注者(在本例中为a@gmail.com)。

我尝试过做这样的事情:

db.collection("tweets")
.where("email", "==", this.state.user.email)//loggedin email
//need to add follower condition as well here so that i get combined tweet

.orderBy("created", "asc")
.onSnapshot(snapshot => {
let oldArr = [];
console.log(snapshot.docs)
snapshot.docs.forEach(doc => {
console.log(doc)
});

最佳答案

您需要对推文集合进行两次(或更多)查询。

一份供您的用户使用,另一份供该用户的每位关注者使用。

还要注意查询条件,集合字段是“by”而不是“email”

像这样:

const makeTweetQueryListener = (email) => db.collection("tweets")
.where("by", "==", email)
.orderBy("created", "asc")
.onSnapshot()

Promise.all([
makeTweetQueryListener(this.state.user.email)
].concat(this.state.user.followers.map(makeTweetQueryListener))
).then(values => {
values.forEach(query => {
query.docs.forEach(console.log)
});
})

编辑 - 更改了上面的代码以添加监听器而不仅仅是查询

关于javascript - firestore 中的查询数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57523586/

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