Flutter Firebase whereQuery in collectionGroup - firebase

Why I cant use whereQuery in collectionGroup.
When I use whereQuery like that;
Query colRef = _firestore.collection("users");
colRef = colRef.where("name", isEqualTo: widget.name);
Its working, but when I use whereQuery like that;
Query colRef = _firestore.collectionGroup("users");
colRef = colRef.where("name", isEqualTo: widget.name);
Its not working, while geting the data, I query whether there is an error by using hasError and if else, and I get an error. and I must use collectionGroup while getting data from firebase.
Is there a solution to use whereQuery in collectionGroup?
Firestore Index Settings
I guess I need to somehow enable the disabled options here, but I don't know how to do it.
In summary I want all users in the application to have access to all kinds of data that I specify in the collection Group.

I need to set the composite and exemption part at the same time, when I set both parts according to the paths I want to query, the problem was solved.

Related

How to make a query from a nested collection in firestore using flutter

I have a nested collection in firestore that I want to make a query from it.
As you can see the first collection called 'businessUsers' and the nested one called 'campaigns',
If I make a query for a field in the 'businessUsers' it's working OK:
return FirebaseFirestore.instance.collection("businessUsers").where('xxx',
isEqualTo:filterBusinessResult ).snapshots().map(_businessListFromSnapshot);
but how can I make a query to 'campaigns' collection field?
I tried
return FirebaseFirestore.instance.collection("businessUsers").doc().collection("campaigns").where('campaignCategory', isEqualTo:filterBusinessResult ).snapshots()
.map(_businessListFromSnapshot);
but it wont work.
Its important to note, that I need all the data with 'campaignCategory' == filterBusinessResult
any idea?
It depends on whether you want to query a specific user's campaigns, or the campaigns of all users together.
If you want to query the campaigns of a specific user, you need to query under their document:
FirebaseFirestore.instance
.collection("businessUsers").doc("your user ID").
.collection("campaigns")
.where('campaignCategory', isEqualTo:filterBusinessResult)
So you have to know the ID of the businessUsers document here.
If you want to query across all campaigns subcollections are once, that is known as a collection group query and would look like this:
FirebaseFirestore.instance
.collectionGroup("campaigns")
.where('campaignCategory', isEqualTo:filterBusinessResult)
The results are going to documents from the campaigns collection only, but you can look up the parent document reference for each DocumentSnapshot with docSnapshot.reference.parent.parent.
When querying something, .doc() requires the id of the document you're trying to get. So it's failing because it doesn't know which document in the businessUsers collection you're trying to fetch a subcollection on. You probably want to use a .collectionGroup() query here. They let you query all subcollections at once (see documentation here). With FlutterFire specifically, it's going to be something like:
var snapshots = FirebaseFirestore.instance.collectionGroup("campaigns")
.where("campaignCategory", isEqualTo: filterBusinessResult)
.snapshots();

Update document value in Firestore Cloud with Flutter, having only a unique key value of such document

I'm new to Cloud Firestore but already made some CRUD operations but now I'm really stuck with this thing.
Each document inside the 'tiposFrota' collection has a key 'nome:' with a unique value, no document will have the same value for the 'nome:' key.
The problem is, whenever the user adds another 'Truck' to some other collections I need to increment the value of 'qtde:' by one, and when they remove 'Truck' the program will increment the number by -1, working as a counter.
I managed to create an operation to update a key value, but only when you have the document id, but in this case the id is autogenerated because they may add or remove standard values from the 'tiposFrota' collection.
FirebaseFirestore.instance
.collection('controladores')
.doc('contadores')
.update({'numFrota': FieldValue.increment(1)}),
I'm really stuck with this, if anyone could please help.
Thanks!
Woah, managed to find a solution by myself, this post Get firestore collections based on values in array list in flutter.
Since the 'nome:' value is unique for each document inside the 'tiposFrota' collection I can use the .where statement as a filter for said document, get the snapshot with all the documents (but only getting one, obviously) and use the 'forEach' method to create a function using the '.id' parameter when calling the document.
FirebaseFirestore.instance
.collection('tiposFrota')
.where('nome', isEqualTo: carMake)
.get()
.then((querySnapshot) {
querySnapshot.docs.forEach((element) {
FirebaseFirestore.instance
.collection('tiposFrota')
.doc(element.id)
.update({
'qtde': FieldValue.increment(1)});
});
}),

Use Firestore autoID to retrieve and display data in Flutter

im new to flutter and dont know exactly what to search for this one but, can we use the auto generated ID like in the picture to retrieve all that data UNDER that ID? if so, how ? In a similar question that I stumbled upon, they use database.reference() but its a Realtime Database and not FireStore
Im using Firebase Cloud Firestore
There is no AutoId in firebase but here is a quick way to set as auto id
Forexample ;
1- create yourModel ( which one u gonna send as model to firebase )
2- DatabaseReference firebaseDatabase;
3- firebaseDatabase =FirebaseDatabase.instance.reference();
4- firebaseDatabase.child("table_name").push().set( yourModel.toJson() );
Also for getting data u can write code like that
var result= firebaseDatabase.child("table_name").once().then(
(DataSnapshot datasnapshot){
Map<dynamic,dynamic> values= datasnapshot.value;
values.forEach((key,value){
print("key:"+key+" value:"+value["name"]);
});
}
);
print(result);
I tried it and works great
Have a nice day !!!
I'm guessing you're asking about subcollections.
If you read a document (by its (auto-generated or not) key), you get back that document. You don't get back data from any subcollection. That will require a separate read operation for each subcollection under the document that you want to read.

Flutter Firestore where clause using map

When a new activity is posted i add a new post document into the collection.
Inside this document i have a map where users add confirmation to the event marking it as true and adding his own id.
var snap = await Firestore.instance
.collection('user_posts')
.where("confirmations.${user.id}",isEqualTo: true)
.getDocuments();
With this snippet i'm able to get all the posts confirmed by the user. The issue here is to get this a index is required to perform this query. And this index can't be generic. I can't create a index for each user.
Some idea of how to get it?
Thanks!!
You'll want to turn the confirmations field into an array, and use the (relatively recent) array-contains and arrayUnion operations.
The equivalent query with an array like that would become:
var snap = await Firestore.instance
.collection('user_posts')
.where("confirmations", arrayContains: user.id)
.getDocuments();
And this way you only need an index on confirmations, which is added automatically.
For more on these see:
the blog post introducing these operations
the documentation on updating arrays
the documentation on array membership queries

Composite query with Orderby in firebase cloud function

is this a valid query for Firestore?
return firestore.collection('users')
.where('userInfo.gender', '==', "male")
.where('userInfo.yob','>=',`${data.minYear}`)
.where('userInfo.yob','<=',`${data.maxYear}`)
.orderBy('count','asc')
.limit(5)
.get()
if i want this query to be valid how do i need to structure this?
or how do i add the indexes?
It is not. If you're doing a greater-than-or-less-than search on one field, you can't then order your results by another field. You're going to have to do the yob query first, and then sort the results afterwards.
For more information, you can check out the documentation here, or this helpful video!

Resources