Firebase query to perform posts search Cloud Firestore [duplicate] - firebase

This question already has answers here:
Firestore group collection query using Flutter
(2 answers)
Fetch all the posts of all the users from Cloud Firestore
(1 answer)
How to retrieve all data from a subcollection of all document
(1 answer)
Closed 1 year ago.
I have posts(collection) -> userid(document) -> userposts(collection) -> postid(document) -> fields (postname,description).
How can I perform search based on postname? I want to get post from all users.
I have following and followers collection
following -> userid(document)->userfollowing (collection) -> all the user ids(documents).
followers -> userid(document)->userfollowers (collection) -> all the user ids(documents).
I have a timeline page the current logged in user should be able to see all the post from users to whom he has followed.
I am ready to change the structure if this is not correct.

You can use collectionGroup query with where():
final query = Firestore.instance
.collectionGroup('posts')
.where('postname', isEqualTo: 'post_name_to_search')
This will return document(s) from posts sub-collection of all users that matches the provided name.

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

issue with cloud firestore firebase query in flutter

I haveposts(collection) -> userid(document) -> userposts(collection) -> postid(document) -> fields (postname,description)how can i perform search based on postname i want to get post from all users
i have following and followers collection
following -> userid(document)->userfollowing (collection) -> all the user ids(documents)
followers -> userid(document)->userfollowers (collection) -> all the user ids(documents)
I have a timeline page the current logged in user should be able to see all the post from users to whom he has followed
(i am ready to change the structure it this is not correct)
I have a timeline page the current logged in user should be able to see all the post from users to whom he has followed
In this case you would have to first fetch UIDs of all users that the current user has followed i.e. read the userfollowers sub-collection documents. If there is any limit on how many users can a user follow, I'd recommend storing those UIDs in an array in user's document itself so it won't cost you N reads everytime you fetch user's followers (N is number of users that this user follows.)
(i am ready to change the structure it this is not correct)
I'd recommend creating 2 different collections to store users and posts as shown below:
users -> {userId}
(col) (doc)
posts -> {postId}
(col) (doc)
You would have to store a field userId in each post containing the author's UID
Once you have fetched the UIDs, you would have to fetch posts of each user individually. You can use whereIn operator as shown below but that can be used only if you have at most 10 UIDs in the user followings list.
FirebaseFirestore.instance
.collection('posts')
.where('userId', arrayContainsAny: [...theArrayContainingUserFollowingsID])
.get()
.then(...);
However if you have more than 10 users in following, then you would have to fetch each user's posts individually or create batches of 10 and use arrayContainAny as shown above.
You can also paginate your data to save reads and fetch data that user has requested instead of all posts from user.

Is my Sub Collection is Also fetched when Fetching the Collection? [duplicate]

This question already has an answer here:
When fetching document from Firestore, am I also getting the collections inside this document?
(1 answer)
Closed 1 year ago.
I have a subcollection "Ratings" inside this "Posts" collection so when i get any post will this collection will be fetched automatically or i have to reference it separately. And if this subcollection Ratings is fetched with the post so it'll be count as a separate read or same as the Post read?
final CollectionReference postsCollection =
FirebaseFirestore.instance.collection("posts");
response = await FirebaseFirestore.instance
.collection("posts")
.get();
Getting a collection will NOT get the subcollections. The subcollections need a separate read.... and reading collection or subcollection considered read.

Fetch documents from multiple subcollections - Firebase [duplicate]

This question already has answers here:
Firestore query subcollections
(11 answers)
Closed 3 years ago.
I'm creating a web app for admin with firebase integration, this web app is used by admin to monitor posts or comments posted by user from Android or iOS app developed in ionic.
I'm using Firebase firestore, and following is the database design
posts/{postsDocument}/comments/{commentsDocument}.
The comments here is sub-collection for postsDocument that holds all the comments for a particular post. Also postDocument and commentsDocument contains Firebase uid of the user.
My problem is, whether it's possible to fetch all the comments commented by a particular user. I can query a single collection, but in this scenario commentsDocument is a subcollection and i want to fetch all comments across all the post by a user for monitoring purpose.
You can check firebase collection group query
var commentsQuery = db.collectionGroup('comments').where('commentOwnerID', '==', userId);//userId - firebase id of the user who commented
commentsQuery.get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, ' => ', doc.data());
});
});
Also you might have to create index that supports your query, check console for the the link for creating index

Query Firestore to get documents in a range of documentIDs [duplicate]

This question already has answers here:
Google Firestore - How to get several documents by multiple ids in one round-trip?
(17 answers)
Closed 4 years ago.
I'm developing a Flutter app using Firebase and Cloud Firestore.
In Firestore I have a collections of Users.
I want to perform a query who give me a list of Users with documentId in a range.
Example
My database:
> Users --> docId1 --> {name: "Domenico"}
> --> docId2 --> {name: "Antonio"}
> --> docId3 --> {name: "Maria"}
My desidered query is something like:
Select name from Users
where documentId in (docId2, docId3)
who gives me ["Antonio", "Maria"].
On documentation I've found how to filter by a document key but not a collection by a range of ducumentId.
Can you help me to perform this query or to understand if I'm doing something wrong?
Thank you.
You can't query on a range of id.
You have to do Two distinct query
var query = firestore.collection("users").doc(docId);
But if you just want to filter on user Name you can do this
var query = firestore.collection("users").where('name', isEqualTo: 'Domenico');
This kind of query is one of the disadvantage of using firestore.

Resources