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.
Related
i have created an array of strings "challengeMember" in Firestore database and i want to add data to it when user clicks a button, my database:
in my code am trying to update the array, every time user join a challenge, the challenge name will be added to this array i know how to access the array using:
FirebaseFirestore.instance.collection("Users").doc(user!.uid).update({'challengeMember': widget._challengeName});
but the problem with this it is not specifying the array index and it is not checking whether the index is empty or not, so how can i dynamically access this array and keep adding values.
Firestore has a special trick to add an array, and it goes like this:
await FirebaseFirestore.instance.collection('users').doc(uid).update({
'tokens': FieldValue.arrayUnion([token]),
});
See the FieldValue documentation on how to manipulate arrays.
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
});
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]),
});
})
I am making an app that helps you decide which country you should visit, based on answers in a survey. I have created a collection in which each doc has a map (keys) with bool-fields.
For example Collection 'Countries' - doc 'Belgium' - field 'keys.party': false
Based on the answers of the user I would like to filter the docs to come to one or more countries that fit their choices. How do I store these answers to query the docs, so I can use them on the result page in a Streambuilder? What's the best way to achieve this?
I also created a collection of users (anonymous) when the survey starts it creates a user doc. I was thinking about storing the answers in there .. and then comparing it to the Country 'collection', but I don't know how to accomplish that.
In need of advice.
by reading your answer there are multiple ways to achieve what you want. So as I understood a user fills out a form and based on the entered data after the user submits the form a list of countries should pop up that fit the filter, correct?
First option -> Filtered database query: When the user hits submit you navigate to the next screen and before everything loads use a FutureBuilder that executes a function that makes a call to the database before the rendering process or just use a stream builder. The call going to Firebase can look something like this:
FirebaseFirestore
.collection('countries')
.where('keys.party', isEqualTo: false)
.where(...)
.where(...)
.orderBy("keys.party", descending: false)
.snapshots()
In the where clauses you can parse the criteria entered by your user. Firebase might spit out something that you need to create an index to search properly but it filters all the data and only returns the data that fits the criteria
Second option -> Filter locally: You can also pull all the countries from Firebase, save them to a list and then filter locally.
countries = documents
.where(
(country) =>
country.*yourattribute* == false,)
.toList();
The second option means that you first need to pull all countries from Firebase (more reads might eventually result in higher Firebase costs). I would go with option number one.
If you reopen the app and still want to query filtered countries with the old survey you of course need to store the user-entered data somewhere. I recommend a user collection with the user document and the survey answers either in a separate document in subcollection or in a user document (Just like you suggested). When opening the app again or navigating to the page where the filtered countries are shown just load the survey data before so you can pass it to the function inside the stream builder or future builder. Hope this answers your question.
im working on e-commerce project, im trying to move data in 'cart' collection into 'orders' collection once the user complete with payment so that i can create order history. previously i have no problem moving single data in firestore but since orders can have multiple item, how do i move it all to another collection?
here is the way i found but its not working.
CollectionReference copyFrom = FirebaseFirestore.instance.collection('users').doc(user!.uid).collection('cart');
CollectionReference copyTo = FirebaseFirestore.instance.collection('users').doc(user!.uid).collection('orders');
copyFrom.get().then((value) => {
copyTo.add(value)
});
There is no move operation in the Firestore API, so you'll have to read each document, then write it to its new location, and delete it from its original location. You might want to use a transaction for this.