简体   繁体   English

目前正在将我的 Firestore 发布数据 function 重构为数组存储

[英]Currently refactoring my Firestore post data function into an array storage

Currently I have a dashboard application and when a user adds to their dashboard it does a post request to Firestore to set the data in a certain document.目前我有一个仪表板应用程序,当用户添加到他们的仪表板时,它会向 Firestore 发出发布请求以在某个文档中设置数据。 Here is what that code looks like:这是该代码的样子:

export function createEntry(data) { // Data has a authorId key with the value of the UID
  const userEntry = firestore.collection('userEntries').doc();
  userEntry.set(data);
  return userEntry;
}

So above, a new entry gets created with a random ID that I then use to grab the data to display later.因此,在上面,使用随机 ID 创建了一个新条目,然后我用它来获取数据以供稍后显示。 To get this information later, I loop through all of the entries to see where the authorId matches the user that is log in to return that.为了稍后获取此信息,我遍历所有条目以查看 authorId 与登录用户匹配的位置以返回该信息。

So what I am trying to do is refactor the code so that each document in 'userEntries' is the ID of the user, authorID: UID, and have it be an array where I can keep pushing items into.所以我想要做的是重构代码,以便'userEntries'中的每个文档都是用户的ID,authorID:UID,并让它成为一个数组,我可以继续将项目推入其中。 In return, I can just grab the user array and map over those items to display instead of looping through all my entries and checking.作为回报,我可以抓住用户数组和 map 来显示这些项目,而不是遍历我的所有条目并检查。

What I've tried:我试过的:

export function createEntry(data) {
  const userEntry = firestore.collection('userEntries').doc(data.authorId);
  userEntry.update({ 
    userData: firebase.firestore.FieldValue.arrayUnion(data)
  })
}

So to sum it up, I would like a way to set the document to users ID and push any future entries into their own array, in which I could easily access from the frontend to display.总而言之,我想要一种将文档设置为用户 ID 并将任何未来条目推送到他们自己的数组中的方法,我可以轻松地从前端访问以显示。

Hope you can point me in the right direction, thank you!希望你能指出我正确的方向,谢谢!

You don't actually have to revise the original method.您实际上不必修改原始方法。 If you have the authorId as a field value, you can just query the data using where clause like this:如果您将authorId作为字段值,则可以使用where子句查询数据,如下所示:

const uid = auth.currentUser.uid;
firestore.collection().where('authorId', '==', uid).get();

With this method, you are not getting the entire collection and looping through to see which one is written by the user.使用这种方法,您不会获取整个集合并循环查看用户编写的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM