Deleting document inside subcollection by using where in Firebase Flutter? - flutter

I want to delete document inside subcollection using where, how can I achieve this?
I can delete document inside subcollection using their document Id, but in some case if we don't know the id, we need to use where method.
This is direct method.
await FirebaseFirestore.instance
.collection('customerDB')
.doc(customerId)
.delete();
I have to achieve in this case:
await FirebaseFirestore.instance
.collection('merchantDB')
.doc(merchantId)
.collection('store')
.doc(storeId).collection('customers')
.where('customerId',isEqualTo:customerId).

Use get() to get snapshot from query, then you can delete the returned result.
// return a QuerySnapshot future, which contain list of matches documents
final snapshot = await FirebaseFirestore.instance
.collection('merchantDB')
.doc(merchantId)
.collection('store')
.doc(storeId).collection('customers')
.where('customerId',isEqualTo:customerId).get()
// delete all matches
for (var doc in snapshot.docs) {
doc.reference.delete();
}

Related

I want to get documents IDs from specific collection in firebase firestore

I have flutter app with firebase firestore in firestore I have on collection inside the collection there is few documents I want to get these documents IDs and put them in list<Strings> to use them in listview.seperated so I can click on one Item and move to another page where I can find the fields of specefic documents but I can't achieve that is there anyway to do that thanks
I try every thing to get the documents Id but nothing work with me I am new to flutter and firebase please help thanks
use doc.id to get ID of document:
List<String> iDs = [];
FirebaseFirestore.instance
.collection('buying2')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc.id); //this is document ID
iDs.add(doc.id);
});
});

Why is vs code saying the method '.getDocuments' and the getter documents are not defined for types Query and QuerySnapshot respectively?

void _getQuestions() async {
// Query Firestore for questions with the specified tags
Query query = await _firestore
.collection('questions')
.where('tags', arrayContainsAny: widget.tags);
QuerySnapshot querySnapshot = await query.getDocuments();
setState(() {
_questions = querySnapshot.documents;
});
importing cloud_firestore.dart.
I expected the errors to leave, but they are still around.
The method to get the documents is called get() in Flutter, not getDocuments().
I recommend keeping the Firebase documentation handy for this sort of thing, for this case that'd be the section on getting multiple documents from a collection

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

I want to delete a document from collection in Firestore

I want to delete a document from a collection in Firebase Firestore. I wrote a method, but it's not working and does not delete anything. I need help, and this is my method:
final couponsReference = FirebaseFirestore.instance.collection("Coupons");
Future<void> Deletecoupon() async {
// displayToastMassage('try1', context);
String s=couponsReference.doc().id;
couponsReference.doc(s).delete().catchError((s){
print(s);
});
displayToastMassage('Coupn Code has been deleted sucsseflly', context);
To delete a document you need the documentId of that specific document. In your deletecoupon method you should pass in the documentId and could then use the await keyword to => await couponsReference.doc(documentId).delete();
To delete a particular document from a collection is very easy you just need one thing that documents documents I'd which you want to delete :
FirebaseFirestore.instance .collection("blogs").doc(widget.postid).delete();

How to update a Firestore document after querying in Flutter

I am trying to figure out how to update my document after I query the one I want to update. Here is the code I came up with:
Firestore.instance.collection("Social_Posts").where(data["postTitle"], isEqualTo: "postTitle").where(data["postContent"], isEqualTo: "postContent")
.snapshots()
.listen((event) {print("hh");});
Whenever I perform this query to find the correct document, I would like to update the document by adding a number to it.
It is possible to update the document from inside, The easier way to do that would definitely be to use the documentID and to increment the value Firestore has a special property, FieldValue.increment(1). Using this you can easily increment a field.
Lets say the field in the document you want to increment by 1, is "numberField".
Updated code using async/await style:
onTap: () async {
setState(() {
_title = data["postTitle"];
_content= data["postContent"];
});
print(_title);
print(_content);
QuerySnaphot snapshot = await Firestore.instance.collection("Social_Posts")
.where("postTitle" , isEqualTo: _title)
.where("postContent", isEqualTo: _content)
.getDocuments();
if(snapshot.documents.isNotEmpty)
{
snapshot.documents.forEach((doc){
doc.reference.updateData({"views" : FieldValue.increment(1),});
});
}
}
The numberField will be incremented without needing to make an extra call to know the present value.
EDIT : You were making a mistake in the .where() method
You can do that by using the document id you quired from inside the listen function in your case by using the event.documents[0].documentID assuming that your query returns one document only and then you can call the updateData method from Firestone package
Your code might looks like this:
Firestore.instance.collection("Social_Posts")
.where(data["postTitle"], isEqualTo: "postTitle")
.where(data["postContent"], isEqualTo: "postContent")
.snapshots()
.listen((event) {
Firestore.instance
.collection("Social_Posts")
.document(
event.documents[0].documentID)
.updateData(
updateEvent) //Add here the new object you want to
.whenComplete(() {
// You can add your desire action after the row is updated
}
});
You can check package page for more information https://pub.dev/packages/cloud_firestore
And if you want to check a sample on how to perform CRUD functionalities you can check this repository: https://github.com/sayed3li97/flutter_firestore_crud