Reputation: 700
In my Fitness app by now I have only one collection users
where every user has his own document. And in this document is stored all of the data from one user. Now I want to create a new collection plans
so that every plan has his own document too. How can I handle it that the plans are saved by the right user? Because now the plan isnt saved anymore in the user document. Or is this the false way of data modeling?
class FireBaseHandler {
Future is_user_registered(String email) {
return FirebaseFirestore.instance
.collection('users')
.where('email', isEqualTo: email)
.get();
}
Future register_new_user(email, password) {
print(email + "->" + password);
return FirebaseFirestore.instance.collection("users").doc(email).set(
{
"email": email,
"password": password,
"token": -1,
"plans": [],
},
);
}
Upvotes: 1
Views: 1031
Reputation: 50830
You can create a sub-collection plans
in every user document. The structure would look something like this:
users -> {userId} -> plans -> {planId}
(col) (doc) (col) (doc)
Here every plan has a dedicated document. This will also prevent you from hitting the 1 MB
max document size by not having all plans in an array in the same document. You can easily query all plans of a user by:
FirebaseFirestore.instance.collection('users').doc("userId").collection("plans")
Upvotes: 4
Reputation: 138824
While @Dharmaraj answer will work, please also note that this is an alternative solution for that, in which you can use a more flatten database structure. I have answered a question a few days ago called:
In your case that would be:
Firestore-root
|
--- users (collection)
| |
| --- $uid (document)
| |
| --- //user details
|
--- plans (collection)
|
--- $planId (document)
|
--- uid: $uid
In this way, you can also have each "Plan" as a separate document in the "plans" top-level collection.
Upvotes: 2
Reputation: 34
My suggestion is under collection "plans", create documents with name matching user_id of a user and store his data there. It becomes easier for you to even select documents based on user_id.
Upvotes: 0