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();
Related
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);
});
});
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();
}
I want to order the documents in Firestore. The default Firestore documents list consist of alphabetic characters which get created automatically. But I don't want that. I just want to see my newly added document added at the top of my documents list. How do I do that in flutter? It would be very helpful if you provide me with a code for that. The code I use to create a collection is:
Future<void> userSetup() async {
String user = FirebaseAuth.instance.currentUser?.displayName as String;
CollectionReference users = FirebaseFirestore.instance.collection(user);
final hours = time?.hour.toString().padLeft(2, '0');
final minutes = time?.minute.toString().padLeft(2, '0');
users.add({
"customerId": FirebaseAuth.instance.currentUser?.uid.toString(),
"customerName": FirebaseAuth.instance.currentUser?.displayName,
"customerEmail": FirebaseAuth.instance.currentUser?.email,
"selectedTime": '${hours}:${minutes}',
"selectedDate": DateFormat('dd/MM/yyyy').format(date!),
});
return;
}
But I am unable to set my own document id. Please help me with the issue. Thanks in Advance
From the Flutterfire documentation, the set() method is the one you should be using to be able to specify your own document IDs instead of add(). Keep in mind that if the document ID you specify already exists in your database, the whole existing document will be replaced. This is a sample usage as found in the documentation:
CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> addUser() {
return users
.doc('ABC123')
.set({
'full_name': "Mary Jane",
'age': 18
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
}
It seems that documents are ordered alphabetically in the Firestore console, so your custom document IDs should follow alphabetical order as you require. Not to be confused with retrieving documents from Firestore in a particular order, which is done with the orderBy() method.
Can anyone tell me how to create a field Id that is equal to the Document ID. I have done like below however is very inconsistent sometimes the documentID is equal field ID other times not. I want them to always be the save.
void saveOrders() async {
await _db.collection(_collectionOrders).add(
{
"id": _db.collection(_collectionOrders).document().documentID,
}
).then((value){
});
}
thanks in advance.
You could do this in two steps:
Create your document without the id:
DocumentReference doc = await _db.collection(_collectionOrders).add({'your': 'data'});
Update the newly created document and add the id property:
await doc.update({'id': doc.id});
You can now be sure that you inserted the right documentId.
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