How to get data as different subcollections and documents from firebase?

41 Views Asked by At

I am working on a project with Firebase and I am really struggling to get data when the collection structure gets a little bit complicated.

Firestore.firestore().collection("Projects").document("SharedProjects").collection(currentUser).addDocument(data: Project)

Firestore.firestore().collection("Projects").document("SavedProjects").collection(currentUser).addDocument(data: Project)

This is my path to upload data to Firebase. As you can see the name of the subcollection "currentUser" is defined and there will be too many different users and different projects.

When I try to get "document(project)" (with addSnapshotListener) I would like to show the projects regardless of who is the "currentUser". For example, I sort all of the "SharedProject" of all users by uploaded date. (not to sort by date one user's projects and then the second one's)

Like this:

1.post:Firestore.firestore().collection("Projects").document("SharedProjects").collection(User1).addDocument(data: Project) uploaded 4.st 2.post:Firestore.firestore().collection("Projects").document("SharedProjects").collection(User2).addDocument(data: Project) uploaded 3.st 3.post:Firestore.firestore().collection("Projects").document("SharedProjects").collection(User2).addDocument(data: Project) uploaded 1.st 4.postFirestore.firestore().collection("Projects").document("SharedProjects").collection(User3).addDocument(data: Project) uploaded 2.st

display order should be : 3post-4post-2post-1post, not should be : 1post-2post-3post-4post or any other order. I could not find any clear explanation on Firebase doc's

I tried to fetch like this and it failed: Firestore.firestore().collection("Projects").document("SavedProjects").collection().addDocument(data: Project)

1

There are 1 best solutions below

3
Alex Mamo On

There will be too many different users and different projects.

There is no problem in having multiple users in a collection. Cloud Firestore is optimized for storing large collections of small documents.

I would like to show the projects regardless of who is the "currentUser".

In that case, I would recommend you create a single collection that will contain all projects of all your users. In this way, you'll be able to create a collection reference that points to that collection and get all projects, no matter who the user is.

You can replace your actual structure if you find this new schema more convenient, or copy the projects in this new collection. If you're new to the NoSQL database, please note that duplicating data is a quite common practice. Besides that, this technique is called denormalization. If you want to learn more, you can check my answer in the following post: