Reputation: 3971
I would like to know what is the best practice to save users preferences in my firestore database. I would try to explain with an example...
I have this kind of Document in my "users" Collection (the name is random generated by Firebase) with 3 fields :
In my Android project, when I want to search the Document of the user "DFDDE45554SDC", I search where user_uid = "DFDDE45554SDC".
I have this kind of Document in my "users" Collection (the name is created with the UID of the user) with 2 fields :
In my Android project, when I want to search the Document of the user "DFDDE45554SDC", I just search the Document "DFDDE45554SDC".
I specify : I don't want duplicate users. So, what is the best practice (security, optimisation,...) ? Why ?
Upvotes: 3
Views: 1700
Reputation: 6926
I would suggest that Case 2
is more effective, for a few reasons:
usersCollection.document(userId)
is simple to construct and is a direct DocumentReference
, rather than a Query
, therefore:
DocumentReference
can be stored in the Firestore database, whereas a Query
cannot.DocumentReference
would likely scale better than instructing the Firestore database to perform a filter query using whereEqualTo("user_uid", userId)
(although with indexing, the performance difference is likely negligible at this point).Query
will always return a collection of results (even if there is only 1), rather than the exact document.The only real incentive I can think of to use Case 1
would be to standardise your document naming scheme with other collections in your database, but this doesn't really matter so much with Firestore.
For a quick example of the two in Android:
Case 1
db.collection("users")
.whereEqualTo("user_uid", "DFDDE45554SDC")
.limit(1)
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
// Even with limit(1), we still receive a collection
// so iterate this to obtain the desired document
}
}
}
});
Case 2
db.collection("users")
.document("DFDDE45554SDC")
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful() && task.getResult() != null) {
// We have access to the single desired document directly
DocumentSnapshot document = task.getResult();
}
}
});
Upvotes: 7