Retrieve multiple items in Firestore

左心房为你撑大大i 提交于 2021-02-19 07:43:09

问题


I have the following data structure in Firestore:

{
  items: [
    itemId1: {},
    itemId2: {},
    itemId3: {}
  ],
  users: [
    userId1: {
      itemIds: [
        "itemId1",
        "itemId3"
      ]
    }
  ]
}

The goal of this data structure is for many users to have access to and collaborate on the same items. So moving the items into each user would be rather inefficient and difficult.

If I have the userId (userId1), I would like to query the items collection for all items that are within the user's itemIds array.

So, in this example, it would return [itemId1: {}, itemId3: {}].

My application is one using Angular (7.2.1) and Angularfire.

If my data structures are inherently flawed, let me know and I can attempt to change them.

Thanks ahead of time.


回答1:


this.afs.doc('users/' + userId1).valueChanges().subscribe(itemIds=>{
  itemIds.forEach(itemId=>{
    this.afs.doc<Item>('items/'+ itemId).valueChanges().subscribe(item=> {
      console.log(item);
    });
  })
});

you can try this one. the first afs.doc retrieves the itemId array from users collection the forEach traverses through all the itemIds and make another firestore query to items collection with document id as _itemId

I havent run the code. but it should clear the idea of how to query such structures. Hope that answers your question



来源:https://stackoverflow.com/questions/54318631/retrieve-multiple-items-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!