How to arrange documents in Firestore using Flutter through custom document IDs? - flutter

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.

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);
});
});

How can I get a collection inside a QuerySnapshot

On the explore page, I get() the entire users collection to create a user list and search results. Inside each of those user documents is a collection posts that I also need to get to create a GridView of each post. I want to reuse that users collection QuerySnapshot instead of fetching each posts collection again to save money. Is this possible?
Here is my current function:
void fetchUsers() async {
final userRef = FirebaseFirestore.instance.collection('users');
final QuerySnapshot result = await userRef.get();
final docs = result.docs.asMap();
docs.forEach((index, value) {
final profile =
ProfileObject.fromJson(value.data() as Map<String, dynamic>);
usersList.add(UserSearchResult(profile, value.id));
/// Below is the code for getting the posts, not working, need ideas
final QuerySnapshot postsResult = value.get('posts');
final posts = postsResult.docs.asMap();
posts.forEach((index, value) {
final post = Post.fromJson(value.data() as Map<String, dynamic>);
postsList.add(post);
});
});
print(usersList);
print(postsList);
}
Here is the structure of my Firestore:
users
uid (doc)
posts (collection)
info (fields)
uid (doc)
posts (collection)
info (fields)
It is not possible to call a collection to get all sub-collections. You should restructure your database to include sub-collection data in document itself. You can use a map or list for that. But remember, calling everything in one go may end up in slow performance and you might end up losing your customers. So the best way is to include the info in every posts' documents. That way, you won't loss your money and user won't feel lag in performance.
It is not possible. You fetch a document, then fetch the (sub)collection under it.
Subcollection data are not included in the initial document snapshots because Firestore queries are shallow. There shouldn't be any cost savings that you can do there?
See the similar Q&A:
Firestore: Get subcollection of document found with where

How to retrive all the documents of firestore at once using flutter?

I am building an Appointment Booking application want to retrieve all my documents from firestore at once on a button click. I used this:
Future<void> userAppointmentHistory() async {
String collectionName =
FirebaseAuth.instance.currentUser?.displayName as String;
String doc_id = "YyWqd9VlB1IdmYoIIFTq";
await FirebaseFirestore.instance
.collection(collectionName)
.doc(doc_id)
.snapshots()
.listen(
(event) {
print(
event.get("selectedDate"),
);
},
);
}
From the above code, I am getting only the specified document id details. So please help me modify the above code so that I get all the document details as I want to display these details on cards as my booked appointment history.
Here you are passing the doc id String doc_id = "YyWqd9VlB1IdmYoIIFTq";
You don't want to pass that if you want the full documents.
just pass the collection reference.
Follow the below code
fetchData() {
CollectionReference collectionReference =
FirebaseFirestore.instance.collection(collectionName);
collectionReference.snapshots().listen((snapshot) {
setState(() {
document = snapshot.docs;
});
print(document.toString);
});
}
Rudransh Singh Mahra,
It's as easy as putting text widget in our application.
Solution
You did it in right way but by mistake you have passed a specific id of documents in doc() as doc('YyWqd9VlB1IdmYoIIFTq'). you just need to remove that id from there and you may get your desired output.
What actually happens :
In your query you pass specific docId. So that it will returns that specified id document from your collection. To get all the documents from that collection you just need to do as follows,
Future<void> userAppointmentHistory() async {
String collectionName =
FirebaseAuth.instance.currentUser?.displayName as String;
// String doc_id = "YyWqd9VlB1IdmYoIIFTq";
await FirebaseFirestore.instance.collection(collectionName).doc().get()
}
And you will get your desired output if collectionName is valid and exist in firestorm database.

How to get the document id from a firestore document in Flutter?

In my App a user can have many different gymplans. So I have a collection where every gymplan has his own document. When creating a new plan I want to store the document id inside the document so that I have access to this document with the id.
When creating a new document firestore automatically create a unique id which is fine. But how can I get this id inside my code? So far my code to create a new plan looks like this:
Future createPlan(String planName, List exerciseNames, List rows) async {
return await usersCol.doc(myUser.uid).collection('plans').add({
'planId': /// here i want to save the document id firestore creates
'name': planName,
'exerciseNames': exerciseNames,
'rows': rows,
});
}
You'd have to create the document first. Then use set() instead of add(). So:
final ref = usersCol.doc(myUser.uid).collection('plans').doc();
return await ref.set({
'planId': ref.id,
'name': planName,
'exerciseNames': exerciseNames,
'rows': rows,
});

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();