Flutter firestore query on document array field - flutter

I've got this firestore database.
There is a 'users' collection containing documents of users. Each user has their own information such as name and a cart. I would like to get all the 'carts' of a particular user in a stream. How would you go about with the query?

await FirebaseFirestore.instance.Collection("users").doc("docIdHere").get().then((.
document) {
//it will get the first item in the cart with index zero
document.get("cart")[0];
//then do what you want
});

Related

Flutter: How to Delete an Array Item in Multiple Documents of a Collection?

I am working on deleting documents and removing items when a user deletes their account. In this case, I have a Firebase collection chats that holds an array users for all of the users within that chat. When someone deletes their account, I want that specific user to be removed from the users array. Here is how I am getting the docs:
var chatsUserIn = await instance.collection('chats').where('users', arrayContains: currentUserReference).get();
And that query is working fine. So if the user is in multiple chats (likely), then it will return multiple documents. However, what I cannot figure out how to do it go through each one of those docs and delete the user from the array users within the document. I do not want to delete the document completely, just remove the user from the array. I know I need to use some various of FieldValue.arrayRemove() but I cannot figure out how to remove the user from each individual document. Thanks for your help!
Update: I tried the following, but it did not delete the user from the array.
chatsUserIn.docs.forEach((element) => FieldValue.arrayRemove([currentUserReference]));
You want to update these documents, so at the top level it's an update call:
chatsUserIn.docs.forEach((doc) {
doc.reference.update({
'users': FieldValue.arrayRemove([currentUserReference])
});
});
You actually want to update a group of Firestore documents. Cloud Firestore does not support the write queries to group documents, this in contrast to read queries witch are also possible on a group of documents.
You must have the doc ID to create a reference to it, and then make an Update request.
db.collection("chats").where("users", arrayContains
: userReference).get().then(
(res) => res.mapIndexed(doc => doc.id))
onError: (e) => print("Error completing: $e"),
);
then, you can send an Update query for each doc of the ID's results:
resultIDs.mapIndexed(id => {
final docReference = db.collection("chats").doc(id);
docReference.update({
"users": FieldValue.arrayRemove([currentUserReference]),
});
})

How to check if array value exist in a document?

see firestore image here
i have document in firestore which has array of products now am struggling how to check if products already exist in such array so that user should not add same product multiple times.how to check for the exixtance of product in that array.
await Firestore.instance.collection('COLLECTION_NAME').document('TESTID1').get().then((doc) {
if (!doc.data()["usercart"].contains(something)) {
// add to cart
}
});
You could also store a local array of the cart when you first fetch them. That way there is no need to read from the database. However, this could be problematic if multiple users are logged in to the same account, but can easly be avoided by using a stream.

Unable to fetch document in flutter firestore

I have a field with name boughtBy, it contains all the ids of the user who have bought the coupons. So, I am trying to show only those coupons which don't have the currentUsers id in the field boughtBy which is an array.
My Code:-
QuerySnapshot snapshotForCoupons=await couponsReference.where('visibility',isEqualTo: true).where('boughtBy',whereNotIn: [currentUser.id]).limit(10).get();
but the problem is it is still showing the coupon which contains the currentUser id.
According to the documentation your query should be written like this:
QuerySnapshot snapshotForCoupons = await couponsReference.where('visibility',isEqualTo: true).where('boughtBy', 'not-in', [currentUser.id]).limit(10).get();

Update FireStore Document Id Using Flutter

I want to update firestore document Id Check This
First, you cannot update the id of a document in Firestore. You will have to copy your document with the new id and delete the old one.
But why do you want to do this, especially within the Users collection? You will lose the link between the Firebase Auth Users and the Users details in your Firestore database.
You can't update the document id directly. For that you first need to make a new document with your updated Id and then delete the previous one.
First of all you need to get the document and store the snapshot value in the variable document.
DocumentSnapshot snapshot= await Firestore.instance.collection('Users').document('yourId').get();
var document=snapshot.data;
After that you can
Firestore.instance.collection('Users').document('newId').setData(document);
Firestore.instance.collection('Users').document(document.id).delete();

flutter Issue in getting subcollection from document in firebase

I have an issue, I can't get subcollection from the document:
I have firestore db with
collection: collectionName
Inside collection documents and inside one document subcollection "items"
collectionName
Document1
Items <- subcollection
Item1
Item2
I use the following code but the items subcollection can't be retrieved from my db....`
```
QuerySnapshot snapshot = await Firestore.instance
.collection('collectionName')
.orderBy("order")
.getDocuments();
```
`then`
```
snapshot.documents.forEach((document) {})
```
The document doesn't have the items subcollection
You can not access a sub-collection like that. Last year, the team working at firestore released a new feature called the Collection Group. If you want to access the items collections try doing this:
Firestore.instance.collectionGroup('items')
This will contain all documents in the items sub-collection regardless of how deeply nested it is. Take a look at this for more information on collection groups.