Firestore - order documents by document field in subcollection - flutter

I have a Flutter app where users can rent items from each other with Firestore RTDB. rental documents have a chat collection that stores the chats between two users:
rentals (collection)
rental_1 (document)
chat (collection)
message_timestamp_1 (document)
message_timestamp_2 (document)
users (array, document field)
user_id_1 (String)
user_id_2 (String)
rental_2 (document)
chat (collection)
message_timestamp_1 (document)
etc.
I have a page in my app that is a listview of all the rentals that the user is involved in (simple arrayContains on the users field). Basically, I want to show all the chats the user is involved in. However, I would like to order this list by most recent chat (like any normal messaging app). Is there a way to achieve this without having to store and update a lastUpdated field in the rental document (thus creating two writes each time a message is sent)?

Adding that lastUpdated field in the rental document and querying the latest rental documents in which a user is involved using array-contains and ordering by lastUpdated field will solve your problem. As you have mentioned this will cost you two writes per message and can lead to a billing trap as a lot of messages can be expected in the chats sub-collection.
Alternatively you can create the chats collection as a top-level collection with a field rentalId so that you can query on this top-level collection to show the recent rental chats the user is involved in. This will eliminate the two writes you have to perform when writing a single message to the firestore.
Hope that helps.

Related

How to sort by a field in a sub-collection in firebase cloud firestore in flutter

I am trying to query a cloud firestore database and i need it to return all the documents in the chats collection sorted by the timestamp field which is a field that all the documents in the messages sub-collection have.
i tried writing a query like this.
FirebaseFirestore.instance.collection("chats").orderBy("messages.timestamp", descending: true)].get(),
but it does not return any documents when actually there are some documents there.
Firestore can only order or filter on data in the documents that it returns. There is no ability to order or filter on data outside of those documents.
So if we want to order chats in the timestamp of the last message in that chat (a common use-case), you'll have to include a lastMessageTimestamp field in the chat document itself, and update that whenever a message is written in its messages subcollection. With that lastMessageTimestamp field in place in each chats document, you can then order and filter on that.
Create a new collection called messages and store all messages for every user there (with a user id field). Reference the message uid's via an array in each chat. This way you can easily query for the messages associated with a chat session then sort them.

Create a document that references another document on Firestore collection

I want to create a reference in my collection Masterclasses for users who bought that masterclass. So, the workflow in my code:
User is registering
User is buying that masterclass
Now, I want to add a new document in masterclasses in the new collection called "subscribers" asigned for that user, after purchasing.
The question is, do I have to create the documents with auto generating IDs and add a field userId, then query all the documents and search if my logged in user is equal to that userId, or alternative solution to create the document itself with user id and search by doc id equality?

Querying subcollections in Firestore using Flutter

I am trying to take all records from sub collection in Firestore.
Below is my table structure.
Restaurants (Main table) --> RestaurantID (document) --> Reviews(Collection) --> ReviewID (document) --> multiple review details with their own uniqueID and will also have reviewDate field.
What I am trying to achieve is I want to list all reviews written on particular date.
If I pass RestaurantID then I am getting records but how to get all records without passing RestaurantID?
Is this possible to achieve in my current table structure? Or must I change it?
If you want to get all reviews for all restaurants, you can use a so-called collection group query (Flutter).
This type of query gets documents from all collections with a given name, so in your case Reviews.

Firestore: Order by sub-collection field

First of all, this is not a regular question. It's little complicated.
App summary
Recipes app where users can search recipes by selected ingredients (collection ingredients exists in firestore db). I want to store for every ingredient statistics how much did users search with that selected ingredient, so I can show them later at the top ingredients which they used mostly for searching recipes.
This is how my collection looks like:
http://prntscr.com/nlz062
And now I would like to order recipes by statistics that created logged in user.
first = firebaseHelper
.getDb()
.collection(Constants.INGREDIENTS_COLLECTION)
.orderBy("statistics." + firebaseHelper.getCurrentUser().getUid() + ".count")
.limit(25);
If logged in user hasn't yet searched recipes with ingredients, then it should order normally. Anyway the query above is not working. Is it possible this use case to be done with Firestore.
Note: Statistics may exists or may not for logged in user, it all depends on his search.
You can't query and documents by fields that don't immediately exist within the document. Or, in other words, you can't use fields documents within subcollections that are not in the named collection being queried.
As of today (using the latest Firestore client libraries), you could instead perform a collection group query to query all of the subcollections called "statistics" for their count field. However, that will still only get you the statictics documents. You would have to iterate those documents, parse the ingredient document ID out of its reference, and individually get() each one of those documents in order to display a UI.
The collection group query would look something like this in JavaScript:
firestore
.collectionGroup("statistics")
.where(FieldPath.documentId())
.orderBy("count")
.limit(25)
You should be able to iterate those results and get the related documents with no problem.

Two ID fields in one collection

I would like to understand how to do the following when inserting a new collection in MongoDB.
As understand it, a new ObjectID is generated for each record (using SQL terminology here) inserted into a collection - you do not have to specify an ID field.
Now I already have a User Profiles collection and I want to create a User Rating collection, where forum users rate other forum users.
The collection would include a rating (1-5) but I also want to specify an ID field for the user being rated ('User_Rated_ID', and the individual who rates him/her('User_Rater').
This is where I get a bit confused, as for each new record in the User Profiles collection, a unique object ID will be generated. Should IDs generated from that collection be used when I want to a insert a new record into the 'User Rating' collection?
There are different ways to do this depending upon the access path of your data, but to think of it in a relational sense your UserRating collection would have three ids: a surrogate id that identifies the document, the raterId, an _id from User that corresponds to the user who did the rating, and the ratedId, an _id from User that corresponds to the user who was rated.
This will allow you to query for ratings that correspond to a user or rater by their _id.