Fetch documents from multiple subcollections - Firebase [duplicate] - firebase

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

Related

How to fetch documents from a collection without certain fields from Firestore? [duplicate]

This question already has answers here:
Is there a way to select only certain fields from Firestore?
(1 answer)
How to access a specific field from Cloud FireStore Firebase in Swift
(5 answers)
How to access some fields of firestore in flutter? [duplicate]
(1 answer)
How to get value of some field in firebase firestore android?
(4 answers)
Closed 2 months ago.
I have a collection let's say "files" and a "file" document has 2 main properties (field) : name and content.
(note: I know storing files in a Firestore is not a good idea but that's just an example, let's assume the files are just text files)
When my app opens I want to be able to fetch all user's file names but not the content :
files = [{name: 'a'}, {name: 'b'}, {name: 'c'}, ...]
The reason is obvious I don't want to pull files' content unless the user explicitly ask for from the UI, minimizing the size of data being pulled from Google Cloud and reducing the cost over time.
But collection(db, 'users', user.uid, 'files') seems to return all docs data. Even worst! if one "file" document change, all the docs and their content are being pulled again from the UI onSnapshot listener...
Reading the TypeScript doc I don't see an option to do atomic selection on docs' fields. Am I missing something?

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

firebase realtime db checking a record for exist [duplicate]

This question already has answers here:
Test if a data exist in Firebase
(3 answers)
Closed 4 years ago.
I am using angularfire2 wth my ionic app and have sign in with facebook enabled.
When first time a user logs in using the fb then i naturally dnt have any record of it in my firebase DB. I want to create a user node using the facebook returned uid as the node.
The way i can retrieve it is like below. I can check by seeing if it has child objects etc. But is that the way recommended to do this kind of checks? I also don't see how to add subscribe or then to it as i would assume this should be async operation for me to wait until it confims me that user does not exist yet. Please advise
const userRef = this.db.object("/users/" + uid)
Simply building a reference to some location in the database (as shown in the code above) says nothing about whether or not data exists at that location. The location needs to be queried in order to figure out of data exists there.
The sample code get from firebase web API document.
var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
updateStarCount(postElement, snapshot.val());
});

How to query by item existance in array on Firestore? [duplicate]

This question already has answers here:
Firestore: Query by item in array of document
(5 answers)
Closed 4 years ago.
I have read this https://firebase.google.com/docs/firestore/solutions/arrays but I still couldn't figure out how it solves the issue of querying not-hardcoded user-generated items in array.
Let's say I have a Party collection:
Party {
name: "Birthday party",
invitees: [56448, 869987, 230232, 202030] # user id's of invited people
}
How can I query only parties where I'm in the invitees array without making an index for each possible ID?
https://firebase.google.com/docs/firestore/solutions/arrays
Limitations
The solution shown above is a great way to simulate array-like structures in Cloud Firestore, but you should be aware of the following limitations:
Indexing limits - A single document can have only 20,000 properties in order to use Cloud Firestore built-in indexes. If your array-like data structure grows to tens of thousands of members, you may run into this limit.
So the short answer is no.
If I were using Firebase Database, I would create a cloud function to watch the party/invitees branch on creation and modification, then propagate the invitation to a branch on the userID profile. Because you can be invited and uninvited, the changeset contains old and new and you can remove invitations from people who are in the previous but not in the next.
I haven't explored Cloud Functions for Firestore (yet) but I suspect that you can do something similar.
If you follow the method described in the documentation you point to (i.e. https://firebase.google.com/docs/firestore/solutions/arrays) and instead of storing the users in an array you save an object like
Party {
name: "Birthday party",
invitees: {
"56448": true,
"869987": true,
"230232": true,
.....
}
}
you will be able to query like
var yourUserID = .....; //e.g. '869987'
db.collection('invitees')
.where('invitees.' + yourUserID, '==', true)
.get()
.then(() => {
// ...
});
And as the doc says "This technique relies on the fact that Cloud Firestore creates built-in indexes for all document fields, even fields in a nested map.", so no worries for maintaining the indexes.

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