Reputation: 11
I need to conditionally retrieve fields of current user's doc. Here is my Firestore db structure.
I need all map type objects (setup1, setup2, setup3...) and their fields, nothing else.
It is possible to conditionally get the needed fields of current user's doc as follows:
const userRef = collection(db, 'users');
const q = query(userRef, where('uid', '==', userID), where('config1', '!=', false));
const userDocs = await getDocs(q);
But I cannot do that as users have only read permission for their own doc:
match /databases/{database}/documents {
match /users/{uid} {
allow read, write: if request.auth.uid == uid;
}
}
In addition, it is not possible to use "where" without "query":
const userRef = doc(db, 'users', userID); // can't use "where" here
// const userRef = doc(collection(db, 'users'), userID) // same here
const userDoc = await getDoc(userRef);
setUserData(userDoc.data());
Is it possible to somehow use "where" above or to filter fields from userDoc.data()?
Upvotes: 1
Views: 529
Reputation: 50840
I need all map type objects (setup1, setup2, setup3...) and their fields, nothing else.
That's not possible using the Firebase Client SDK. You can only fetch the whole document. Firestore Node.JS SDK does support selecting required fields only but that is meant to be used on server side so you'll have to use Cloud functions or something similar.
But I cannot do that as users have only read permission for their own doc:
query(userRef, where('uid', '==', userID), where('config1', '!=', false));
This query will not return any document because there's no config1
field in the root of document.
Is it possible to somehow use "where" above or to filter fields from userDoc.data()?
It might best to create a sub-collection setups
. Then you should be able to run all your required queries.
users -> { userId } -> setups -> { setupId }
If each setup sub-document has the configN
field the following query should return all users setups where the given config is true:
const userSetupRef = collection(db, `users/${userId}/setups`);
const q = query(userSetupRef, where('config1', '!=', false));
Upvotes: 1