Im trying to get data from firebase but im a bit struggling . I have this videos collection where I saving video ids and thenevery video has documetnfield and also a sub collection called user votes . In side that im saving the user votes from the ratingbarindicator
this is how to collection looks
So what I want is every document of the user votes sub colletion and then the each rating field .
but how can I do that ?What I want is calculating that together Hope anyone can help
To read the data from all (sub)collections with a given name, you can use a collection group query.
FirebaseFirestore.instance
.collectionGroup('uservotes')
.get()
...
Also see:
Is wildcard possible in Flutter Firestore query?
Fetch all the posts of all the users from Cloud Firestore
you can go through collection and document like this with firebase:
final querySnapshot = await FirebaseFiresotre.instance.collection('videos').doc([theVideoDocumentID])
.collection('uservotes').get();
final docs = querySnapshot.docs;
for(final doc in docs) {
final data = doc.data();
//handle each document here
}
Related
I wants to achieve one query which i'm trying for few hours in FireStore Database, Please check the below image,
The Query I want to do is, In the document which I marked, will have a list of group id (combination of 2 userIds in each , userId1-userId2), I want to query this document by having one userId that contains in the group id (before or after hyphen) and returns a list of snapshots , which should be used for StreamBuilder in a list widget.
For Example:
I may have 'abcdefghijkl' userId, I want to check each document ID that contains this userId, and returns a list of snapshots which matches.
Thanks in Advance!
I don't think the query you want is possible, since there is no operation to check if a document id contains something. I would recommend adding a participants array to the document and than use an array-contains query, see also here.
There are several ways to achieve what you're after - a list of users relating to a given document - but I think you should rethink your data structure first. Each message document should have a users field that is an array of Firestore document IDs which would contain 1 or more document IDs of the users that this message relates to.
With that, you can easily query the database for all messages where a given user is referenced:
final messages = db
.collection('messages')
.where('users', arrayContains: userId)
.get();
BTW, to take things a step further, I would structure my data like this:
user {
displayName: '',
email: '',
messages: [
{
authorId: userId,
content: '',
users: [userId, ...],
sentOn: '',
},
...
]
}
With this you can do two things:
Fetch all messages created by the user:
final userMessages = db.doc(userId).collection('messages').get();
Fetch all messages where user participated:
final allUserMessages = db
.collectionGroup('messages')
.where('users', arrayContains: userId)
.get();
Check out the Firestore docs, as they have plenty of examples there.
I have created a simple app using flutter and firebase firestore database. There are 'users' collections and each user has 'posts' collections. Each post may have one or more posts added by different users.
I am trying to get all the posts regardless of users. However, my current function was written for reading records only shows the posts relevant for login user, not all the posts.
Stream<QuerySnapshot> readItems({required String collectionName}) {
CollectionReference detailCollection = _firestore
.collection(mainCollectionName!)
.doc(userUid)
.collection(collectionName);
return detailCollection.snapshots();
}
Here, I pass 'users','login user's uid' and 'posts' as mainCollectionName, userUid and collectionName respectively. Can anybody guide me how do I get all the posts regardless of users?
After searching I found a solution here. The following method gives the desired output.
Stream<QuerySnapshot> readItems({required String collectionName}) {
Query<Map<String, dynamic>> detailCollection = _firestore.collectionGroup(collectionName);
return detailCollection.snapshots();
}
It is possible to get all sub collections data from all the documents in a collection. Try this way
_firestore
.collection(`${mainCollectionName}/*/${collectionName}`)
.get()
Refer to this page for more details about querying collections and sub collections - https://firebase.googleblog.com/2019/06/understanding-collection-group-queries.html
please how can I get all the value of my IndividualTaxData subcollection in Flutter.
First, you must get the reference to the parent document:
DocumentReference parentRef = Firestore.intances.collection('TaxData').document(taxDataId);
You can do the previous part with a direct reference to the document (like the code above) or with a query. Later, you must get the reference of the subcollection and the document that you get the information:
DocumentReference subRef = parentRef.collection('IndividualTaxData').document(individualTaxId);
And finally, get the data:
DocumentSnapshot docSnap = await subRef.get();
For you to return a simple document, you can use the following code for it.
var document = await Firestore.instance.collection('IndividualTaxData').document('<document_name>');
document.get() => then(function(document) {
print(document('character'));
// you can print other fields from your document
}
With the above code, you will reference your collection IndividualTaxData and then load it's data to a variable that you can print the values.
In case you want to retrieve all the documents from your collection, you can start using the below code.
final QuerySnapshot result = await Firestore.instance.collection('IndividualTaxData').getDocuments();
final List<DocumentSnapshot> documents = result.documents;
documents.forEach((data) => print(data));
// This print is just an example of it.
With this, you will load all your documents into a list that you iterate and print after - or that you can use with another method.
In addition to that, as future references, I would recommend you to check the following links as well.
Query a single document from Firestore in Flutter (cloud_firestore Plugin)
How to use Cloud Firestore with Flutter
Le me know if the information helped you!
My application is using firestore database. I design categories and its subcategories of the content by using subcollection.
To make offline mode feature;
I want to save this firestore data to sqflite database.
I learned that I convert firebase data map to text for sqlite
But I counl't find a way to locate the subcollections.
var catagorySnapshots =
await _firestore.collection("categories").getDocuments();
List _list = [];
catagorySnapshots.documents.forEach((_snapshot) {
CategoryInformation categoryInformation = CategoryInformation();
CategoryItem curCategory =
CategoryItem.fromCollection(_snapshot.documentID, _snapshot.data);
categoryInformation.categoryList.add(curCategory);
print(curCategory.title);
//
// sub collections
//
});
I know its too late to answer, this might help someone else.
You have to try getting the information from snapshot.data['field'] like so and covert it to text as well.
Let me know of that works.
I want to achieve is when flutter screen loads a document should create in firestore in following order.
Document > Sub Collection > Document > Data Fields
I manage to create documents and sub collections in above order, but the first Document appear in italic. That's because the child collection, documents creating before parent document created.
But I couldn't able to fix the issue. I've modified the code now it's not even creating the document. Before this It created in italic mode. Now it's not at all.
Here is the code.
getCurrentUser().then((user) {
DocumentReference todayReference = firestoreInstance.collection('attendance').document(todayDate);
firestoreInstance.collection('profiles').where('user_id', isEqualTo: user).snapshots().listen((onData) {
onData.documents.forEach((f) {
CollectionReference todaySubCollection = todayReference.collection(f.documentID);
DocumentReference attendanceReference = todaySubCollection.document(f["name"].toString().toLowerCase());
Map<String,dynamic> mapData = new Map<String,dynamic>();
mapData['attendance_status'] = true;
mapData['in'] = true;
mapData['out'] = true;
firestoreInstance.runTransaction((transaction) async {
await transaction.set(attendanceReference, mapData);
});
});
});
});
Here getCurrentUser() is returning the logged in user id.
Each profiles assigned to a user.
So, What I'm trying to do is, once user logged in a document should create under attendance collection named today's date.
Then looping through each profiles where user_id is matched with logged in user, the matching results will be store as sub collection under today's date with profiles name field.
Then under the name (document), a transaction needs to run to set details like attendance_status, in & out.
Following images will show how previously documents created.
I need to find a way to create documents, collection without in italic mode. Any help would be appreciated.
"Italicized" documents are virtual/non-existent as mentioned in the docs. If a document only has a sub-collection, it will be a virtual/non-existent document. A workaround for this is by writing fields in the document, like what you've mentioned in the comments.