How can I use multiple order by in real time database flutter to order data by specific field? [duplicate] - firebase

This question already has answers here:
Query based on multiple where clauses in Firebase
(8 answers)
Closed 2 years ago.
I am trying to short "realtime database" result according to "date" in flutter. But I cant use multiple orderByChild('child_name'). It throw an error. My code is
final String path = 'jsondata';
final _dbRef = FirebaseDatabase.instance.reference();
_dbRef.child(path)
.orderByChild('trade_code').equalTo('GP')
.once()
.then((DataSnapshot snapshot) {
snapshot.value.forEach((key, value) {
print(value);
});
});
The result is
Result
Now I want to sort the data by Date.
How can I do that?

It's not possible to use multiple oder at the same time in Firebase Realtime Database. Please check the following doc:
Firebase Realtime Database Query
To achieve that type of complex query I prefer that you should migrate from the Realtime Database to Firebase Cloud Firestore. Check the following resource:
Simple and Complex Dynamic Query in Could Firestore
Your Firestore instance would be:
FirebaseFirestore.instance
.collection('products')
.where('trade_code', isEqualTo: 'GP')
.orderBy('date')

Related

Flutter: Better way to update many documents in a single call [duplicate]

This question already has answers here:
Can Firestore update multiple documents matching a condition, using one query?
(8 answers)
Firestore update all documents in collections
(6 answers)
How to do a bulk update in Firestore
(4 answers)
Closed 9 months ago.
I have a function that allows a user to change their username, simply using firebase update({}). Every time a user sends a message in my chat page, it saves it as a documents on firebase with related data, user name, time message was sent etc.
The function below is for a chat page, which works how I want it to. it takes whatever the current users username and updates all past messages with the users new current username. I want to know if their is a better way to achieve this.
How can I change a single value in any amount of documents, which obviously have different ids, in one single call?
List<String> testList = []; //<--- List of document IDs of previous messages user has sent
FirebaseFirestore.instance
.collection('users')
.doc(loggedInUser.uid)
.update({'messageID': testList});
for (var item in testList) {
var collection = FirebaseFirestore.instance
.collection("chatrooms")
.doc(chatroom)
.collection("users")
.doc('ggg')
.collection("userMessage");
collection
.doc(item) // <-- Doc ID where data should be updated.
.update({'username': loggedInUser.userName.toString()}) // <-- Updated data
.then((_) => print('Updated'))
.catchError((error) => print('Update failed: $error'));

how to get collection list from document Id in flutter Firestore? [duplicate]

This question already has answers here:
Flutter & Firebase: Return list of collections
(2 answers)
Fetching all collections in Firestore
(3 answers)
How to list subcollection on firestore? [duplicate]
(1 answer)
Closed 1 year ago.
i want "a9XvvHPEvhfDWTXe8HqPqWuP2gg1" this documentId collection list.
FirebaseFirestore.instance
.collection('tbl_FriendList').doc(
'a9XvvHPEvhfDWTXe8HqPqWuP2gg1').get().then((event) {});
You can't do that with the Flutter sdk. You'll need to restructure your data.
Retrieving a list of collections is not possible with the mobile/web
client libraries. You should only look up collection names as part of
administrative tasks in trusted server environments. If you find that
you need this capability in the mobile/web client libraries, consider
restructuring your data so that subcollection names are predictable.
https://firebase.google.com/docs/firestore/query-data/get-data#list_subcollections_of_a_document
As per you image, seems like there is no document in this ID. You only have sub-collections.
To get sub-collection you have to improve your query and you should know your sub-collection name as mentioned below
await FirebaseFirestore.instance
.collection('tbl_FriendList')
.doc('a9XvvHPEvhfDWTXe8HqPqWuP2gg1')
.collection('collectionPath')
.get();
Or you have to store data in db like this
a9XvvHPEvhfDWTXe8HqPqWuP2gg1 > collectionName > documents
FirebaseFirestore.instance
.collection('tbl_FriendList')
.doc('a9XvvHPEvhfDWTXe8HqPqWuP2gg1')
.collection('collectionName')
.add({'data': 'data123'});
after that you can get data as mentioned below
FirebaseFirestore.instance
.collection('tbl_FriendList')
.doc('a9XvvHPEvhfDWTXe8HqPqWuP2gg1')
.collection('collectionName')
.get()
.then((value) => {});
This query will return all data you have in collectionName sub-collection.

How can I sort Firestore stream based on timestamp in Flutter [duplicate]

This question already has answers here:
how to use orderBy after .where(arrayContain) flutter firebase firestore
(2 answers)
Cloud Firestore: FAILED_PRECONDITION: The query requires an index
(5 answers)
Closed 1 year ago.
I am trying to generate a list using stream builder in flutter and want to sort that list based on firestore timestamp. I have already tried this code given below
```stream: FirebaseFirestore.instance
.collection("posts")
.doc(widget.eid)
.collection("users")
.orderBy("postDate", descending: true)
.where("ownerId", isEqualTo: user.userId)
.snapshots(),```
and the error i got is: "The query requires an index. You can create it here:"
I have resolved this issue by adding indexing on firestore
i think you making two mistake first you useing ordey by before where thats a wrong way to use the where so put where first and then use order by and second your first collection field should not empty if its empty thsts shows italic so you cant fetch data. according firestore its means its delted by defalut. so i make a correction in query.
stream:FirebaseFirestore.instnce.collection("posts") .doc(widget.eid) .collection("users") .where("ownerid",isEqualto:user.userId) .orderBy("postdate",decsending:true) .snapshots(),

Firebase/Firestore: Is it possible to query .where(x == foo || x == bar)? [duplicate]

This question already has an answer here:
How to accomplish WHERE IN query in Cloud Firestore [duplicate]
(1 answer)
Closed 3 years ago.
I have a collection of users, which looks like this:
Each follower/following document is structured like this:
{
uid: ...,
}
I want to create a query that satisfies these criteria:
Get the users that you are following
Ordered by their 'lastPosted' time (so you're getting the users who have posted most recently first)
Since the follower/following subcollections only contain references to full user documents, and not the full documents themselves, it's not as easy as just querying the following subcollection.
This is what I've tried:
database
.collection('users')
.doc(myUid)
.collection('following')
.get()
.then(followings => {
database
.collection('users')
.orderBy('lastPosted', 'desc')
.where('uid', '==', following[0] || following[1] ...)
})
Which doesn't work. I have also thought about this:
database
.collection('users')
.orderBy('lastPosted', 'desc')
.where(myUid exists in their followers subcollection)
I'm not sure where to go from here, or whether firestore even allows this.
See:
https://firebase.google.com/docs/firestore/query-data/queries#query_limitations
Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.

Firebase database functions onWrite/Create/Delete user UID [duplicate]

This question already has answers here:
Getting the user id from a database trigger in Cloud Functions for Firebase?
(2 answers)
Closed 5 years ago.
Is is possible to get the user UID of the user who wrote/updated/deleted data from the database?
When you are using Firebase authentication you can get the uid of the authenticated user using the following lines of code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
String uid = firebaseUser.getUid();
}
On the other hand, you need to know that Firebase does not store meta-data or other informations regarding write operation. To achieve this, you need to create your own mechanism.
In your case, when a user creates a record, store his uid on a location from where you can query for that particular uid and use it for what you want.
In case you are trying to determine this within Cloud Functions i recomand you take a look at Firebase Cloud Functions and at jacobawenger's answer from this post

Resources