Reputation: 2402
I have a Firestore database structure like this:
Songs:
- song1
- artistName
- songCover
- song2
- song3
I want to be able to grab all the users that have favorited an specific song
In the past I made an structure like the following
FavoriteSongs
- IDSong1
- userID1 (with favorited the song)
- artistName
- songCover
- userID2
Songs:
- song1
- artistName
- songCover
In the previous structure, I made an exact copy of each song inside a user's id node. However, when a song changes its cover, this forces me to change every document inside the FavoritedSongs where the ID of the song that changes matches the IDSong key of FavoriteSongs.
Reading about collection group queries, I thought I could do something like this:
Songs:
- song1
- artistName
- songCover
-> Favorited (Subcollection):
- userID1
- song2
- song3
This wat I could retrieve all the songs that a particular user has favorited, and I could get the song with all the updated values, since changing the cover of a song will only affect one document.
Is this possible, and if so, how can I write the query?
Upvotes: 3
Views: 1981
Reputation: 317477
If you want to write a collection group query that finds documents among subcollections (named "favorited") where some document property (also "favorited") is true:
firestore.collectionGroup("favorited").where("favorited", "==", true)
Each user would need to be able to write their own document in the subcollection with an ID the same as their UID in order to set this boolean property. So, to mark a favorite, a user would:
firestore
.collection("songs")
.doc(songId)
.collection("favorited")
.doc(userId)
.set({ favorited: true })
Upvotes: 3