Flutter Firebase timestamp searchquery - firebase

In my apps user can post. And post store in firebase like this
I wanna fetch my all post which posted in last week. I need some filter in my search query. But I dont know how can I.
this my search query
_newQuerySnapshot = await Firestore.instance
.collection("posts")
.orderBy("createdAt", descending: true)
.startAfterDocument(lastDocument)
.limit(5)
.getDocuments();
I need like this .where( //posted in last week )
Please help me .

I solved like this.
var beginningDate = DateTime.now();
var newDate=beginningDate.subtract(Duration(days: 1));
_newQuerySnapshot = await Firestore.instance
.collection("posts").where("createdAt",isGreaterThanOrEqualTo: newDate)
.orderBy("createdAt", descending: true)
.limit(5)
.getDocuments();

Or you can do like this
var startfulldate = admin.firestore.Timestamp.fromDate(new
Date(1556062581000));
db.collection('mycollection')
.where('start_time', '<=', startfulldate)
.get()
.then(snapshot => {
var jsonvalue: any[] = [];
snapshot.forEach(docs => {
jsonvalue.push(docs.data())
})
res.send(jsonvalue);
return;
}).catch( error => {
res.status(500).send(error)
});

You can use where query in firestore, https://firebase.google.com/docs/firestore/query-data/queries#query_operators

Related

Flutter Firestore create new Array every time function called

As per the question I'd like to add a new array every time I call my addPredection function for example I'd like it to look like this.
Currently its just updating the current value everytime
My code is as follows:
///add prediction function
Future<String?> addPrediction() async {
var currentUser = FirebaseAuth.instance.currentUser;
var todaysDate = DateTime.now().toString();
var doesExist = await FirebaseFirestore.instance
.collection('collection')
.doc(currentUser!.uid)
.get();
if (doesExist.exists == true) {
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.uid)
.update({
'Predictions':
FieldValue.arrayUnion([todaysDate,'angry', 'Happy'])
});
}
if (doesExist.exists == false) {
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.uid)
.set({
todaysDate: FieldValue.arrayUnion(['angry', 'Happy'])
}, SetOptions(merge: false));
}
For adding items you also have to apply the SetOptions but with the merge set to true, like this:
var todaysDate = DateTime.now().toString();
FirebaseFirestore.instance
.collection('userMoods')
.doc(currentUser!.UID).set({
todaysDate : ['angry', 'happy']
}, SetOptions(merge: true));
I did it on my end and I believe they come out the way you want:
The merge: true on the SetOptions what it does is that it appends to the existing document. The set method by default overrides the existing fields unless the merge: true option is there.

Firebase query doesn't get documents with a specific field

I'm running a query to get all documents from firebase containing a field of location contains, say 'Nairobi'. The structure of my database is /posts/[userId]/userPosts/[postId].
Now, when I specify the userId in my code, I get the documents.
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('posts')
.doc("1092987983578079255")
.collection('userPosts')
.where('location', isGreaterThanOrEqualTo: '${placemark.locality}')
.get();
setState(() {
posts = snapshot.docs.map((doc) => Post.fromDocument(doc)).toList();
isLoading = false;
});
However, when I try to get all the documents within the entire posts collection, I get null results.
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection('posts')
.where('location', isGreaterThanOrEqualTo: '${placemark.locality}')
.get();
setState(() {
posts = snapshot.docs.map((doc) => Post.fromDocument(doc)).toList();
});
I have tried using the code
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collectionGroup("userPosts")
.where('location', isGreaterThanOrEqualTo: '${placemark.locality}')
.get();
setState(() {
posts = snapshot.docs.map((doc) => Post.fromDocument(doc)).toList();
isLoading = false;
});
but I get the error Operation was rejected because the system is not in a state required for the operation's execution. If performing a query, ensure it has been indexed via the Firebase console.
given that, it is only querying through one criterion, I don't believe that a composite index is necessary but I, still, have created one.
adb logcat doesn't give me the link to create an index even if I wrap the code in try to catch the error e.
What am I missing?

How to access data of a filter query in firestore flutter?

I want to search for the user from his mobile number. If the user found then show his other information like Name, Surname.
The search query is working fine. But I'm not able to access the data. Below is my function to get the result of the query. When I print the data its just prints [Instance of 'QueryDocumentSnapshot']
getData() async {
final QuerySnapshot result = await FirebaseFirestore.instance
.collection('CommonData')
.where(
'Mobile_Number',
isEqualTo: mobileNumber,
)
.get();
final List<DocumentSnapshot> resultDocument = result.docs;
print(resultDocument);
}
Try this
getData() async {
String mobile_number;
String name;
String surname;
final QuerySnapshot result = await FirebaseFirestore.instance
.collection('CommonData')
.where(
'Mobile_Number',
isEqualTo: mobileNumber,
)
.get();
result.docs.forEach((value) {
mobile_number = value.data()['Mobile_Number'];
name = value.data()['Name'];
surname = value.data()['SurName'];
});
print("Mobile Number: " + mobile_number);
print("Name: " + mobile_number);
print("SurName: " + mobile_number);
}
Since you make the assumption that your DB does contain one and only one User per Mobile Number, you might want to enforce this assumption:
Future<Map<String, dynamic>> getData(String mobileNumber) async {
return FirebaseFirestore.instance
.collection('CommonData')
.where(
'Mobile_Number',
isEqualTo: mobileNumber,
)
.get()
.then((snapshot) => snapshot.docs.single.data())
.catchError(
(e) {
if (e.message == 'No element') {
print("Couldn't find User for Mobile Number $mobileNumber");
} else if (e.message == 'Too many elements') {
print("Found duplicate Users for Mobile Number $mobileNumber");
}
return null;
},
test: (e) => e is StateError,
);
}

Query a document value in a nested collection in firebase

I need to get the values from a document with this schema in Firebase:
COLLECTION => DOCUMENT => COLLECTION => DOCUMENT
userPolls => userId => dailyPolls => 20200825 => pollDate: "2020/08/25"
status: "Under PUM"
statusCode: "pum"
uid: "zwQnrrBdNCemWyXEW2LHmw8LejA2"
This is my attempt at it. But I think I am getting it wrong in flutter
final CollectionReference userPollCollection =
Firestore.instance.collection('userPolls');
Future getPoll() async {
final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('yyyy/MM/dd');
final String formatted = formatter.format(now);
var pollDate = formatted;
var docRef = await applicationUser
.document(userId)
.collection('dailyPolls')
.document(pollDate);
docRef.get().then((onValue) => {print(onValue.data['status'])});
}
I know that this is not right. Can you please show me how? Thank you.
EDIT
For reference, this is how I ADD data to the firestore db:
Future setPoll(UserPoll userPoll) async {
var dt = userPoll.pollDate.replaceAll('/', '');
return await userPollCollection
.document(userId)
.collection('daillyPolls')
.document(dt)
.setData({
'uid': userId,
'pollDate': userPoll.pollDate,
'status': userPoll.status,
'statusCode': userPoll.statusCode
});
}
This is how I try to get it
Future getPoll() async {
final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('yyyy/MM/dd');
final String formatted = formatter.format(now);
var pollDate = formatted;
var dt = pollDate.replaceAll('/', '');
var docRef = userPollCollection
.document(userId)
.collection('dailyPolls')
.document(dt);
docRef.get().then((onValue) {
print(onValue.data);
});
}
}
If I use this code based on the help of Peter Haddad, I get a null value when printing my result.data
You have to do the following:
var docRef = Firestore.instance.collection("userPolls").document(userId).collection('dailyPolls').where("pollDate", isEqualTo: pollDate);
var result = await docRef.getDocuments();
result.documents.forEach((result) {
print(result.data);
});
});
Since pollDate is an attribute inside a document then you can use the where() method to query and get the document

How can I get specific document data from firestore querysnapshot?

I got a querysnapshot in a function.
And want to bring the whole querysnapshot to another function (functionTwo).
In functionTwo, I want to get a specific document in the querysnapshot WITHOUT forEach. The specific doc can be changed by different cases.
ref_serial_setting.get()
.then(querysnapshot => {
return functionTwo(querysnapshot)
})
.catch(err => {
console.log('Error getting documents', err)
})
let functionTwo = (querysnapshot) => {
// getting value
const dataKey_1 = "dataKey_1"
// Tried 1
const value = querysnapshot.doc(dataKey_1).data()
// Tried 2
const value = querysnapshot.document(dataKey_1).data()
// Tried 3 (Put 'data_name': dataKey_1 in that doc)
const value = querysnapshot.where('data_name', '==', dataKey_1).data()
}
The result are all these trying are not a function.
How can I get specific document data from querysnapshot??
or
Is there any easy method to change the querysnapshot to JSON?
You can get an array of the document snapshots by using the docs property of a QuerySnapshot. After that you'll have to loop through getting the data of the doc snapshots looking for your doc.
const docSnapshots = querysnapshot.docs;
for (var i in docSnapshots) {
const doc = docSnapshots[i].data();
// Check for your document data here and break when you find it
}
Or if you don't actually need the full QuerySnapshot, you can apply the filter using the where function before calling get on the query object:
const dataKey_1 = "dataKey_1";
const initialQuery = ref_serial_setting;
const filteredQuery = initialQuery.where('data_name', '==', dataKey_1);
filteredQuery.get()
.then(querySnapshot => {
// If your data is unique in that document collection, you should
// get a query snapshot containing only 1 document snapshot here
})
.catch(error => {
// Catch errors
});
Theres an easy way to do this, each QuerySnapshot has a property docs which returns an array of QueryDocumentSnapshots. See QuerySnapshot documentation.
let citiesRef = db.collection('cities');
let query = citiesRef.where('capital', '==', true).get().then(snapshot => {
snapshot.docs[0]; // => returns first document
});
let citiesRef = db.collection('cities');
let query = citiesRef.where('capital', '==', true).get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
from https://firebase.google.com/docs/firestore/query-data/get-data
you can use this code :
const querySnapshot = await getDocs(collection(db, "collectionNaame"));
const docSnapshots = querySnapshot.docs;
for (var i in docSnapshots) {
console.log(i)
const doc = docSnapshots[i].data();
console.log(doc)
Just do
db.doc(<<ref>>).get()
this returns a promise
[here ]: https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document is the link to the docs

Resources