How do you delete a document by timestamp in firestore flutter? - firebase

So I am trying to make a chat app with cloud Firestore and I don't how to delete a document by timestamp.
This is currently how I delete a document.but when I tried it deletes all the document:
onLongPress: () async {
await FirebaseFirestore.instance
.collection('messages')
.doc(
groupChatId)
.collection(
groupChatId)
.orderBy("timestamp",descending: true).get().then((value) => {
for(DocumentSnapshot ds in value.docs){
ds.reference.delete()
}
});
},

try this code:
await FirebaseFirestore.instance
.collection('messages')
.doc(
groupChatId)
.collection(
groupChatId)
.where("timestamp", isLessThan: DateTime.now().microsecondsSinceEpoch-TheNumberOfMicrosencundenTheDocumentCanBeOld).get().then((value) => {
for(DocumentSnapshot ds in value.docs){
ds.reference.delete()
}
});

Related

how to search through firebase

I want to search through my firebase collection and get any document with the specific phonenumber entered, but it keeps returning nothing.
Here is a screensot of my database
Here is the code i used to query it:
await FirebaseFirestore.instance
.collection("users")
.where("mobilenumber", isEqualTo: "+23407063435023")
.get()
.then((QuerySnapshot querySnapshot) { querySnapshot.docs.map((DocumentSnapShot documentSnapshot) {
if (documentSnapshot.exists) {
print("found");
}
});
}).catchError((error) => throw error);
and this is the security rule
The problem was in then, I should have used foreach instead of a map,
await FirebaseFirestore.instance
.collection("users")
.where("mobilenumber",isEqualTo: "+23409056088820")
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print(documentSnapshot.id);
}
});
}).catchError((error) {
print(error);
});
I don't know why though.
Your query searches docs on country, not on phonenumber. Adapt it as follows:
await FirebaseFirestore.instance
.collection("users")
.where("phonenumber", isEqualTo: "12345")
.get()
.then((QuerySnapshot querySnapshot) { querySnapshot.docs.map((DocumentSnapShot documentSnapshot) {
if (documentSnapshot.exists) {
print("found");
}
});
}).catchError((error) => throw error);

How to add data from a subcollection in Firestore to a List?

FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
print(info.toString());
}
I am trying to build a Flutter application using Firestore.My firestore has two collections namely users and friends.Collection users contains documents with locations,names and Collection friends contains documents which each have a subcollection friends that store the Unique IDs of "users" who are friends. This is the output when I execute the above function
I/flutter ( 7773): hello eyHBWGrNoxSMe8cQUqWC
I/flutter ( 7773): []
I/flutter ( 7773): lalala{loc: Instance of 'GeoPoint', dname: hamza ansari}
PROBLEM: The data is not getting stored into the list 'info'. Any help with this would be appreciated :D
.Here is a photo of the friends collection.
And here is a photo of the users collection.
Would really love it if someone could help me out here :)
You can access the documents by snapshot.data.documents then you can get document Id like this
var doc= snapshot.data.documents;
var docId=doc[index].documentID
FirebaseFirestore.instance
.collection('dishes')
.doc(docId)
.collection('ingredients')
.snapshots(),
i think the problem is that you are simply not returning anything in your Future.
try this
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
return info ;
}
The problem seems to be with the conversion of the subcollection to a list. Try the following:
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(Map(Map.fromMap(value.data())));
});
});
});
print(info.toString());
}

Read subcollection from Firestore flutter?

How to read subcollection from flutter firestore. I am using cloud_firestore. I am successfully adding data into firestore but couldn't retrieve it(tried and failed).
I want to retrieve subCollection called product Firestore collection
I tried this I don't have the document ID Because it generated automatically from firestore :
Stream<QuerySnapshot> loadorderdetails(String uid) {
return FirebaseFirestore.instance
.collection('Users/$userid/Orders')
.doc()
.collection("Products")
.where('uid', isEqualTo: uid)
.snapshots();
}
You should try this
FirebaseFirestore.instance.collection("Users/$userid/Orders ").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
FirebaseFirestore.instance
.collection("Users/$userid/Orders")
.doc(result.id)
.get()
.then((querySnapshot) {
//print data
});
});
});
});

Flutter firestore save id to list

how can I save all document Ids From firestore inside a list?
Thats what I tried but I couldn't manage to only save the ID:
List ticketIds = [];
getTicketIds() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
ticketIds = await FirebaseFirestore.instance
.collection("users")
.doc(prefs.getString("userId"))
.collection("tickets")
.get()
.then((val) => val.docs);
Hello you need to loop trough the docs and you can retreive the docs id, here is the code :
Future<List<String>> getTicketIds() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
List<String> ticketIds = await FirebaseFirestore.instance
.collection("users")
.doc(prefs.getString("userId"))
.collection("tickets")
.get()
.then((val) {
List<String> idOfDocuments = [];
val.docs.forEach((element) {
idOfDocuments.add(element.id);
});
return idOfDocuments;
});
return ticketIds;
}

How can I check this in collection?

I have added this collection:
Map<String, String> userDataMap = {
"userName": usernameEditingController.text,
"userEmail": emailEditingController.text,
"account": userType // there is premium and regular account type
};
...
Future<void> addUserInfo(userData) async {
Firestore.instance.collection("users").add(userData).catchError((e) {
print(e.toString());
});
}
And actually I don't know how to get info about account type, I would like to print/get value assigned to "account".
This is what I tried but it did nothing:
var ok = await Firestore.instance
.collection('users')
.where('email', isEqualTo: email)
.getDocuments();
print(ok);
Thank you in advance.
Inside the document, you have a field called userEmail and not email therefore you need to do the following:
var userDoc = await Firestore.instance
.collection('users')
.where('userEmail', isEqualTo: email)
.getDocuments();
userDoc.documents.forEach((result) {
print(result.data["account"]);
});

Resources