Firestore collection group query on document id [duplicate] - firebase

This question already has an answer here:
How to perform collection group query using document ID in Cloud Firestore
(1 answer)
Closed 1 year ago.
I am trying to run the following query:
this.db.firestore
.collectionGroup('members')
.orderBy('dateModified', 'desc')
.where(firebase.firestore.FieldPath.documentId(), '==', uid)
But I get the error:
Invalid query. When querying a collection group by
FieldPath.documentId(), the value provided must result in a valid
document path, but 'X6yL5Ko55jSMWhhoQUO91xVYdEH3' is not because it
has an odd number of segments (1).
Is the only way around this to add the document id to the document?
This is not ideal as I have a lot of existing data...
The document id is the uid of the firebase user.

As the error message says, for an index on a collection group the documentId() field values are actually stored as document paths to ensure unique lookups of those values in the index.
If you want to also query on document ID over a collection group, you will indeed have to store the ID as a field value in each document.
Also keep in mind that it is then possible to get multiple documents for the query, even though that is astronomically unlikely if you use the built-in add() operation.

Adding the uid to the document itself is the only possible way at the moment and then query on that field:
this.db.firestore
.collectionGroup('members')
.orderBy('dateModified', 'desc')
.where("uid", '==', uid)
There was a Github issue for the same and explains why that's not possible.
That's pretty much why I sometimes prefer to store a root level collection members. Each document in the collection will have contain the groupID (or whatever your parent collection is meant for). If you use userID as the key for documents in there then it goes easy.
this.db.firestore.collection("members").doc(uid)
So instead of having a path like: /groups/{groupID}/members/{memberID}, the structure will be like: /groups/{groupID} and all the members will be store in the root level collection 'members'. A document in that collection may look like:
// uid as doc key
{
groupId: "groupID",
...otherFields
}
The catch is if a member can join multiple groups you cannot use the userId as the key.

Related

Flutter cloud firestore : query document->map->array

My db design is above picture. I wanna create a query which returns user where tags are matched. But i didnt any solution to query.
This is my flutter code:
But it doesnt work. How can i query array of map of document?
The courses is an array and not a map so you cannot use the dot notation to query. If the courses is made a collection (or a sub-collection) on it's own then you would be able to query users easily:
users -> {userId}
(col) (doc)
courses -> {courseId}
(col) (doc)
You would have to include a field userId in each course document which would be used to identify which user owns that course.
await firestore.collection("courses").where("tags", arrayContainsAny: tagKeys)
This will return all courses where the tags array contains at least 1 item in the tagKeys list. If you need exact match i.e. all the tags in tagKeys must be present in Firestore document then you would have to restructure the database as mentioned in this answer.
Fetching all matching documents might not be ideal since you just need user IDs that matches the tags. In that case you can store a field which contains tags from all the courses in a single array field in the user document.

Firebase Get document from subcollection using its ID only

Is it possible to fetch a document from a subcollection without parent document ids?
We have a structure like:
RootCollection1
-- SubCollection1
-- SubCollection2
- Document1
-- SubCollection3
-- Document2
-- SubCollection2
-- Document3 [different fields with Document1]
App User will only have the Document1 ID.
I tried implementing a collection group query. Notice that SubCollection2 name appears twice and they have different fields/values. I only want to get the document from one SubCollection2.
Is it possible to fetch the data from document1 without the parent doc id from SubCollection1 and RootCollection1.
If you can't locate a document using its full path (knowing the names of all documents and collections in the path), and you can't use a collection group query, then what you're trying to do isn't possible. You can't focus a collection group query to a specific path - they always consider all documents in all collections with the same name.
You have two viable workarounds:
Change the name of the subcollection so that it's unique and does not overlap with subcollections that should not be queried in a collection group query.
Add a field to the document so you can use it in a filter on a collection group query. You will have to be able to identify which documents you are interested in without considering all documents in all subcollections with the same name. For example, if you have a field called "scope", you can narrow the scope of your collection group query like this:
firestore.collectionGroup('coll').where('scope', '==', 'x')
Or you can store the ID of the document as a field in it, and filter for it:
firestore.collectionGroup('coll').where('id', '==', 'id')
This is all you need:
firestore.collection("Task").doc(taskId).collection("SubTask").doc(subTaskId).get();

Firestore - good practice to use uid of FirebaseAuth as the document index for further relations

i have a simple question regarding if it's a good practice to use the uid of the FirebaseAuth-Service for relations in other collections as the document index. So on login I get the uid of the FirebaseUser. With that I create an user like so:
Now is that a good practice to use this uid as the index of another document somewhere in another collection like this:
Or is it more common to let the index be generated and add an uid field inside the document so that I can query it with 'uid' equal 'my_uid' for example?
I come from the SQL-side and I don't have that much experience about NoSQL and how to sturcture it well. It would be great if someone could give me an advice here.
This is not a problem at all to reuse the same document ID in different collections, whether this id is a user uid (from Auth) or any other value (including an auto generated Firestore id).
Or is it more common to let the index be generated and add an uid
field inside the document so that I can query it with 'uid' equal
'my_uid' for example?
This is also a common approach, which can be interesting for example if you don't want to display the value of a Firestore document id (for example in an an url like https://www.whatever.com/players/-useruid- or https://www.whatever.com/players/-playername-).
Note however that this can generate some "tricky" side effects: for example if you want to avoid having two user profiles with the same user_name, in order to check that into a Transaction, you need to use the user_name as the id of the documents, since, with the Client SDKs it is not possible to execute a query within a Transaction (you need to define a DocumentReference to pass to the Transaction's get() method).

Is it possible to fetch all documents whose sub-collection contains a specific document ID?

I am trying to fetch all documents whose sub-collection contain a specific document ID. Is there any way to do this?
For example, if the boxed document under 'enquiries' sub-collection exists, then I need the boxed document ID from 'books' collection. I couldn't figure out how to go backwards to get the parent document ID.
I make the assumption that all the sub-collections have the same name, i.e. enquiries. Then, you could do as follows:
Add a field docId in your enquiries document that contains the document ID.
Execute a Collection Group query in order to get all the documents with the desired docId value (Firestore.instance.collectionGroup("enquiries").where("docId", isEqualTo: "ykXB...").getDocuments()).
Then, you loop over the results of the query and for each DocumentReference you call twice the parent() methods (first time you will get the CollectionReference and second time you will get the DocumentReference of the parent document).
You just have to use the id property and you are done.
Try the following:
Firestore.instance.collection("books").where("author", isEqualTo: "Arumugam").getDocuments().then((value) {
value.documents.forEach((result) {
var id = result.documentID;
Firestore.instance.collection("books").document(id).collection("enquiries").getDocuments().then((querySnapshot) {
querySnapshot.documents.forEach((result) {
print(result.data);
});
First you need to retrieve the id under the books collection, to be able to do that you have to do a query for example where("author", isEqualTo: "Arumugam"). After retrieving the id you can then do a query to retrieve the documents inside the collection enquiries
For example, if the boxed document under 'enquiries' sub-collection exists, then I need the boxed document ID from 'books' collection.
There is no way you can do that in a single go.
I couldn't figure out how to go backwards to get the parent document ID.
There is no going back in Firestore as you probably were thinking. In Firebase Realtime Database we have a method named getParent(), which does exactly what you want but in Firestore we don't.
Queries in Firestore are shallow, meaning that it only get items from the collection that the query is run against. Firestore doesn't support queries across different collections in one go. A single query may only use the properties of documents in a single collection. So the solution to solving your problem is to perform two get() calls. The first one would be to check that document for existence in the enquiries subcollection, and if it exists, simply create another get() call to get the document from the books collection.
Renaud Tarnec's answer is great for fetching the IDs of the relevant books.
If you need to fetch more than the ID, there is a trick you could use in some scenarios. I imagine your goal is to show some sort of an index of all books associated with a particular enquiry ID. If the data you'd like to show in that index is not too long (can be serialized in less than 1500 bytes) and if it is not changing frequently, you could try to use the document ID as the placeholder for that data.
For example, let's say you wanted to display a list of book titles and authors corresponding to some enquiryId. You could create the book ID in the collection with something like so:
// Assuming admin SDK
const bookId = nanoid();
const author = 'Brandon Sanderson';
const title = 'Mistborn: The Final Empire';
// If title + author are not unique, you could add the bookId to the array
const uniquePayloadKey = Buffer.from(JSON.stringify([author, title])).toString('base64url');
booksColRef.doc(uniquePayloadKey).set({ bookId })
booksColRef.doc(uniquePayloadKey).collection('enquiries').doc(enquiryId).set({ enquiryId })
Then, after running the collection group query per Renaud Tarnec's answer, you could extract that serialized information with a regexp on the path, and deserialize. E.g.:
// Assuming Web 9 SDK
const books = query(collectionGroup(db, 'enquiries'), where('enquiryId', '==', enquiryId));
return getDocs(books).then(snapshot => {
const data = []
snapshot.forEach(doc => {
const payload = doc.ref.path.match(/books\/(.*)\/enquiries/)[1];
const [author, title] = JSON.parse(atob(details));
data.push({ author, title })
});
return data;
});
The "store payload in ID" trick can be used only to present some basic information for your child-driven search results. If your book document has a lot of information you'd like to display once the user clicks on one of the books returned by the enquiry, you may want to store this in separate documents whose IDs are the real bookIds. The bookId field added under the unique payload key allows such lookups when necessary.
You can reuse the same data structure for returning book results from different starting points, not just enquiries, without duplicating this structure. If you stored many authors per book, for example, you could add an authors sub-collection to search by. As long as the information you want to display in the resulting index page is the same and can be serialized within the 1500-byte limit, you should be good.
The (quite substantial) downside of this approach is that it is not possible to rename document IDs in Firestore. If some of the details in the payload change (e.g. an admin fixes a book titles), you will need to create all the sub-collections under it and delete the old data. This can be quite costly - at least 1 read, 1 write, and 1 delete for every document in every sub-collection. So keep in mind it may not be pragmatic for fast changing data.
The 1500-byte limit for key names is documented in Usage and Limits.
If you are concerned about potential hotspots this can generate per Best Practices for Cloud Firestore, I imagine that adding the bookId as a prefix to the uniquePayloadKey (with a delimiter that allows you to throw it away) would do the trick - but I am not certain.

Firestore - query where filter of object in array field

I have question about query in firecloud.
For example, see my document:
i need filter all documents where the account_id is "value" and "approve" is true. How i do it?
I tried: where("members.account_id", "==, "qgZ564nfEaNP3Nt4cW1K3jCeVlY2") and not work:
See, this is a question that not for specific language, just about firestore query, after undestand, i go apply it in my code.
I'm programing in flutter.
If you query like this:
where("members.account_id", "==", "qgZ564nfEaNP3Nt4cW1K3jCeVlY2")
Firebase checks if there's a nested field /members/account_id with the given value. And such a field doesn't exist, because the value is actually at /members/0/account_id.
Since you don't know the position in the array the the ID exists, you instead want to use an array-contains condition. With array-contains Firestore checks if the array you contains the exact member that you specify.
With your current structure you can check if the member exists with:
.where("members", "array-contains", { accountId: "qgZ564nfEaNP3Nt4cW1K3jCeVlY2", approved: true })
So you must know the entire data of the array element in order to use array-contains.
If you only know a single member, while you're storing multiple members, you can't use array-contains. In that case, I recommend adding an additional member_accountIds field to each document, where you store just their account IDs:
member_accountIds: ["qgZ564nfEaNP3Nt4cW1K3jCeVlY2", ... ]
With that in place, you can query like this:
.where("members_accountIds", "array-contains", "qgZ564nfEaNP3Nt4cW1K3jCeVlY2")

Resources