Henry Peregrino
Henry Peregrino

Reputation: 136

How to structute the data properly in firestore?

I'm currently working in a React + Firebase project. In Firestore I need to save the data of users, but currently I don't know which approach to use. There will be two users, Teacher and Student.

1st option: Set a collection of users, each document will have the 'user-type' field which defines if a user is a Teacher or a student. The problem that I saw with this approach is, lets say:

2nd option: Create two collections, a collection of 'teachers' and a collection of 'students'. Then in my system, instead of having a single login button, I will set two login buttons, one to login as a teacher and one to login as a student. Then, for the same example:

Hope I explained myself well, I'm not the best english writter and google translate isn't helping too much. Any help will be appreciated. Thanks in advance.

Upvotes: 1

Views: 55

Answers (1)

Stratubas
Stratubas

Reputation: 3067

So basically in will query the 'users' collection to find data based on the email (email will be unique) and the 'user-type' == 'teacher'

that is not true. If emails are really unique, you don't need to filter by user-type. You don't need to use where. Just create a reference to the document associated with the user and get() it:

const userDoc = await db.collection('users').doc(userEmail).get();

As Nicholas said, you should consider using the UID instead of the email.

users is a really big collection and then the query to get the data of the teacher will impact the UX, since firestore needs to read a considerable amount of documents

that is also not true. Query performance is proportional to the size of your result set, not your data set .

Regarding Nicholas Tower answer,

If you have two .where clauses like this, i think you'll need to create an index. The code should throw an exception which has a url; follow that url, and it will let you create the index (and once its created, the exception doesn't happen any more).

you only need an index if you combine equalities (==) with ranges (>, >= etc). You can combine as many == as you like without an index.

Upvotes: 2

Related Questions