Flutter firestore returning empty array on some documents - flutter

Can one explain to me what's going on with with firestore collection fetching.
I am able to fecth busescollection data under 201 but when I fecth for other 'ids' like 212 I get an empty array when there is clearly data in there.
this is the fecth function
FirebaseFirestore firestore = FirebaseFirestore.instance;
Future<dynamic> getBusesByID(int id) async {
// Create a CollectionReference called users that references the firestore collection
var lines = firestore.collection('lines').doc('$id').collection('buses');
var line = await lines.get();
return line.docs.map((e) => {'id': e.id, ...e.data()}).toList();
}
what is it with the weird behavior?

Related

How to get the List of Document Reference from a Snapshot Document resulting from a Firestore query

I can't seem to figure out how to get a List after querying a specific Firestore collection.
I want the function to:
Query the 'chat' collection on the field 'users'.
Retrieve only the document (should be only one but could be an error and there's more than one) where users, which is a LIST of Document Reference, matches two specific references: chatUserRef and authUserRef
The function should return a list of the Document References referring to this chat collection
This is what I am trying:
import 'package:cloud_firestore/cloud_firestore.dart';
Future<List<ChatsRecord>> getChatDoc(
DocumentReference chatUserRef,
DocumentReference authUserRef,
) async {
// Add your function code here!
final firestore =
FirebaseFirestore.instance; // Get a reference to the Firestore database
final collectionRef =
firestore.collection('chats'); // Get a reference to the collection
final filteredDocuments = collectionRef.where('users', isEqualTo: [
authUserRef,
chatUserRef
]); // Use the `where` method to filter the list of documents
final queryDocuments = await filteredDocuments
.get(); // You can then use the get method on this Query object to retrieve the list of documents AS a Snapshot Document (this is NOT a list of the Documents themselves).
List<ChatsRecord> listChatDocs = [];
// Cast the Snapshot Documents to a map
// Extract the Document Reference ID
// cast the query document to a map for e
// (should I forEach?)
List<ChatsRecord> listChatDocs = queryDocuments.docs.map((e) {
return FirebaseFirestore.instance.doc('chats/$e.id');
}).toList();
return listChatDocs;
}
Try using the arrayContainsAny instead of EqualTo in your where clause.
Like this:
final filteredDocuments = collectionRef.where('users', arrayContainsAny: [
authUserRef,
chatUserRef
]);

Flutter firestore returns length 0 while there is data in firestore

I have the following code in flutter:
QuerySnapshot querySnapshot =
await _firestore.collection("user1#gmail.com").get();
List Data = querySnapshot.docs.map((doc) => doc.data()).toList();
print("Length: ${Data.length}");
Here is my firestore database:
I get the following output:
I/flutter (11484): Length: 0
The Documents for each user email is variable, so I need the length of the documents. Also I need to get to the details of each document like content and title. How to do it? Thanks.
Could you try this:
int size = await FirebaseFirestore.instance.collection(collectionPath).get(GetOptions(source:Source.server))..size;
I will recommend finding a way to store the length of documents as a field in your Cloud Firestore database because calling the get function on a whole collection means filling up the mobile phone memory. (Say you have 500,000 users at least). This makes your app slow
You could have a field called count such that when you add a document, you can use the firebase transaction to update firebase.
For example:
// Create a reference to the document the transaction will use
DocumentReference documentReference = FirebaseFirestore.instance
.collection('users')
.doc(documentId);
return FirebaseFirestore.instance.runTransaction((transaction) async {
// Get the document
DocumentSnapshot snapshot = await transaction.get(documentReference);
if (!snapshot.exists) {
throw Exception("User does not exist!");
}
// Update the follower count based on the current count
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
// Perform an update on the document
transaction.update(documentReference, {'followers': FieldValue.increment(1);});
// Return the new count
return newFollowerCount;
})
.then((value) => print("Follower count updated to $value"))
.catchError((error) => print("Failed to update user followers: $error"));
You can see more documentations here: FlutterFire

Get list of collection from firebase using flutter

I need to get list of collection like
datalist = ["2009" , "2010"]
I can use this code to print what inside the 2009 , but that not i want
final _fireStore = FirebaseFirestore.instance;
Future<void> getData() async {
// Get docs from collection reference
QuerySnapshot querySnapshot =
await _fireStore.collection('data/student_details/2009').get();
// Get data from docs and convert map to List
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
//for a specific field
print(allData);
}
and I need to know about can I filter it
Thank you.
My Firebase view
In Firebase you can not fetch a list of Collections, You have to explicitly mention the name of Collection to fetch it. It means you must have pre-knowledge of name of Collection to fetch it.

flutter firestore how I filter data

I have a collection (Groups) inside it
fields contain information about users who joined the group,
I want to display to the user all groups he joined.
List groupList = [];
void getAvailableGroups() async {
await _fireStore
.collection('Groups')
.get()
.then((value) {
groupList = value.docs;
});
}
I tried to convert from map into array but it gives me array within map this is my code
Future createGroup() async{
GroupRoomModel newGroup = GroupRoomModel(
groupName: groupName.text,
groupRoomId: uuid.v1(),
owner: userModel.uid,
membersList: controller.membersList,
membersListUid: controller.membersListUid.cast() // like this
);
}
...
Also I tried
Future createGroupFunc() async{
GroupRoomModel newGroup = GroupRoomModel(
groupName: groupName.text,
groupRoomId: uuid.v1(),
owner: userModel.uid,
membersList: controller.membersList,
membersListUid: controller.membersListUid.map((e)=> e).toList()
);
...
It might be tempting to try filtering based on something like this:
_fireStore
.collection('Groups')
.where('membersList', arrayContains: 'test#email.com')
This won't work though, as arrayContains only finds something a match when it matches a complete item in the array. You can't use arrayContains to match just a subset of an item.
The common solution is to add an additional array field to your documents with just the property you want to be able to query on. For example:
memberEmails: ['test#email.com', 'test#example.com']
With such an addition field, you can query with:
_fireStore
.collection('Groups')
.where('memberEmails', arrayContains: 'test#email.com')

Get all documents from a Firestore collection in Flutter

I tried with different ways but i can't edit the structure of code
//First way
QuerySnapshot querySnapshot = await db.firestoreInstance.collection('user-history').get();
var list = querySnapshot.docs;
print('MY LIST ===== $list');
//Second way
final CollectionReference collectionRef = db.firestoreInstance
.collection(historyCollection);
print('MY SECOND LIST ===== $list');
collectionRef.get().then((qs) {
qs.docs.forEach((element) {
print('MY doc id ${element.id}');
});
});
In my firebase collection(historyCollection) i have four documents but the debugger returns me empty array []. Is there another way to call all documents in certain collection through flutter?
I'm trying to call this method through FutureBuilder component.
My version of firestore is: "cloud_firestore: ^0.16.0+1"
This should do the trick:
Future<List<dynamic>> getCollection(CollectionReference collection) async {
try {
QuerySnapshot snapshot = await collection.get();
List<dynamic> result = snapshot.docs.map((doc) => doc.data()).toList();
return result;
} catch (error) {
print(error);
return null;
}
}
The entire problem was not from these fragments of code. This problem is came out from this that my collections have subcollections. I read about this and i understand that subcollections can live without their ancestors and the only way to access parents is to do this is directly specify the exact path and name of the document. To work this code in my case was needed to add dummy components of my entire set of collections. For more information please look up these two topics:
-> https://firebase.google.com/docs/firestore/using-console
-> Firestore DB - documents shown in italics