Firebase sets collection but does not retrieve and sees it when i reference it from flutter - firebase

I am trying to create a document and collection following each other
with this reference
CollectionReference att = FirebaseFirestore.instance
.collection('attendance/$_currentClass/pieces');
but when it is created it is shown like that image below
and i can't see documents that has name of "_currentClass" variable.
If we create create it by ourselves it creates properly.
Here top one was created by me and bottom one created inside flutter
What am i doing wrong?

Based on your path your CollectionReference to this subcollection is:
CollectionReference att = FirebaseFirestore.instance
.collection('attendance')
.doc(_currentClass)
.collection('pieces');
Document, you are pointing with italic font does not exist, it was deleted, but before that it had a collection, and pointing that documents on that subcollection were not deleted and they still exist.If you create documents with sub-documents and then delete the top level document from an SDK, the delete is not recursive. So while the top-level document is gone, its sub-documents remain.
Since there is no document anymore, the document itself will not show up in query results. If you need to find this document in query results, you'll want to create an empty document as a workaround.

Related

How to create one stream listening to multiple Firestore documents created from list of documents references in Flutter

Im trying to create one stream, that is using multiple documents references that are stored and fetched from Firebase Firestore.
Lets say I have two collection named users and documents. When user is created he gets document with his id in users collection with field named documentsHasAccessTo that is list of references to documents inside documents collection. It is important, that these documents can be located in different sub collections inside documents collection so I dont want to query whole documents and filter it, in order to save Firestore transfer and make it faster I already know paths to documents stored in documentsHasAccessTo field.
So for example, I can have user with data inside users/<user uid> document with documentsHasAccessTo field that stores 3 different document references.
I would like to achieve something like this (untested):
final userId = 'blablakfn1n21n4109';
final usersDocumentRef = FirebaseFirestore.instance.doc('users/$userId');
usersDocumentRef.snapshots().listen((snapshot) {
final references = snapshot.data()['documentsHasAccessTo'] as List<DocumentReference>;
final documentsStream = // create single query stream using all references from list
});
Keep in mind, that it would also be great, if this stream would update query if documentsHasAccessTo changes like in the example above, hence I used snapshots() on usersDocumentReferences rather than single get() fetch.
The more I think about this Im starting to believe this is simple impossible or theres a more simple and clean solution. Im open to anything.
You could use rxdart's switchMap and MergeStream:
usersDocumentRef.snapshots().switchMap((snapshot) {
final references = snapshot.data()['documentsHasAccessTo'] as List<DocumentReference>;
return MergeStream(references.map(ref) => /* do something that creates a stream */));
});

Fetch data from subcollection document in flutter

This is my data structure. Here are the list of users documents.
and here is the subcollection in every document.
The subcollection is containing strongly typed document which is form.
What I want is to fetch form document (not for the current user) from subcollection workerField from every users document.
what is the implementation method.
If you want to load documents from all workerField collections you can use a so-called collection group query.
So something like:
var docs = await FirebaseFirestore.instance
.collectionGroup('workerField')
.snapshots();
See my answer here for another example: Is wildcard possible in Flutter Firestore query? and more from these search results.

Getting documents length 0, but data is present in firestore

I'm building an e-commerce app but when I query firestore to retrieve data I get documents length 0. Data Is present in Firestore. I have no idea what is causing this issue.
I have added all the dependencies.
Firestore.instance
.collection('Products')
.getDocuments().then((value) => print(value.documents.length));
Why this query is not giving me a total number of documents inside Products.
When I run this Query I get a Correct number of documents inside Fruits.
Firestore.instance
.collection('Products')
.document('ABHISHAK FRUITS').collection('Fruits').getDocuments().then((value) => print(value.documents.length));
The log message is correct - your first query returned no documents.
Notice that IDs of the documents in the console are in italics. This means that the document is not present. The reason why the console is showing these missing documents is because the document ID has a subcollection nested under it, and it's letting you click through to browse them.
Your second query using the subcollection works fine because the subcollection has documents present in it.
The bottom line here is that subcollections are not really "contained" within their parent documents like a traditional computer filesystem. The parents documents can be created or deleted without affecting the any subcollections nested under them.

Firestore query for subcollections on a deleted document

When using the Firebase console it is possible to see all documents and collections, even subcollections where the path has "documents" that do not exist.
This is illustrated in the picture included here, and as stated in the docs and on the screenshot as well. These documents won't appear in queries or snapshots. So how does the console find these nested subcollections, when a query does not return them?
Is it possible, somehow, to list these documents. Since the console can do it, it seems there must be a way.
And if it is possible to find these documents, is it possible to create a query that fetches all the documents that are non-existant but limited to those that have a nested subcollection? (Since the set of all non-existant documents would be infinite)
The Admin SDK provides a listDocuments method with this description:
The document references returned may include references to "missing
documents", i.e. document locations that have no document present but
which contain subcollections with documents. Attempting to read such a
document reference (e.g. via .get() or .onSnapshot()) will return a
DocumentSnapshot whose .exists property is false.
Combining this with the example for listing subcollections, you could do something like the following:
// Admin SDK only
let collectionRef = firestore.collection('col');
return collectionRef.listDocuments().then(documentRefs => {
return firestore.getAll(documentRefs);
}).then(documentSnapshots => {
documentSnapshots.forEach(doc => {
if( !doc.exists ) {
console.log(`Found missing document: ${documentSnapshot.id}, getting subcollections`);
doc.getCollections().then(collections => {
collections.forEach(collection => {
console.log('Found subcollection with id:', collection.id);
});
});
}
});
});
Note that the Firebase CLI uses a different approach. Via the REST API, it queries all documents below a given path, without having to know their specific location first. You can see how this works in the recursive delete code here.
Is it possible to create a query that fetches all these subcollections that are nested under a document that does not exist.
Queries in Cloud Firestore are shallow, which means they only get documents from the collection that the query is run against. There is no way in Cloud Firestore to get documents from a top-level collection and other collections or subcollections in a single query. Firestore doesn't support queries across different collections in one go. A single query may only use properties of documents in a single collection or subcollection.
So in your case, even if one document does not exist (does not contain any properties), you can still query a collection that lives beneath it. With other words, you can query the queue subcollection that exist within -LFNX ... 7UjS document but you cannot query all queue subcollection within all documents. You can query only one subcollection at a time.
Edit:
According to your comment:
I want to find collections that are nested under documents that do not exist.
There is no way to find collections because you cannot query across different collections. You can only query against one. The simplest solution I can think of is to check if a document within your items collection doesn't exist (has no properties) and then create a query (items -> documentId -> queue), and check if has any results.
Edit2:
The Firebase Console is telling you through those document ids shown in italics that those documents just does not exist. Those documents do not exist because you didn't create them at all. What you did do, was only to create a subcollection under a document that never existed in the first place. With other words, it merely "reserves" an id for a document in that collection and then creates a subcollection under it. Typically, you should only create subcollections of documents that actually do exist but this is how it looks like when the document doesn't exist.
In Cloud Firestore documents and subcollections don't work like filesystem files and directories you're used. If you create a subcollection under a document, it doesn't implicitly create any parent documents. Subcollections are not tied in any way to a parent document. With other words, there is no physical document at that location but there is other data under the location.
In Firebase console those document ids are diplayed so you can navigate down the tree and get the subcollections and documents that exist beneath it. But in the same time the console is warning you that those document does not exist, by displaying their ids in italics. So you cannot display or use them because of the simple fact that there is no data beneath it. If you want to correct that, you have to write at least a property that can hold a value. In that way, those documents will hold some data so you can do whatever you want.
P.S. In Cloud Firestore, if you delete a document, its subcollections will continue to exist and this is because of the exact same reason I mentioned above.

Resolve Firestore References

Firebase Firestore has a reference type while defining fields of a document which allows us to add a reference to another document via its "Document path".
For example, I have the document animals/3OYc0QTbGOTRkhXeiW0t, with a field name having value Zebra. I reference it in the array animals, of document zoo/xmo5wX0MLUEbfFJHvKq6. I am basically storing a list of animals in a zoo, by referring the animals to the corresponding animal document in the animals collections.
Now if I query a specific document from the zoo collection, will references to the animals be automatically resolved? Will I the get the animal names in the query result? If not, how can I achieve this?
All document queries in Firestore are shallow, meaning that you only get one document in return for each document requested.
References in a document are not automatically fetched - you will have to make subsequent queries using the references in the document to get those other documents on your own.
Same thing with documents in subcollections - they require separate queries.

Resources