When you go into posts collection there are documents based on userId. And inside a document there is a new collection named userPosts. Inside userposts you can find postId and the details about the post.
I can get specific user post by using this code
postRef = Firestore.instance.collection('posts');
QuerySnapshot snapshot = await postRef
.document(userId)
.collection('userPosts')
.getDocuments();
But I want to get all the user posts without naming a specific user. How could I achieve this?
You can use a collection group query to query documents among all collections with same name.
QuerySnapshot snapshot = await Firestore.instance
.collectionGroup('userPosts')
.getDocuments();
Related
I want to update value of the field's document. I wrote a query but it doesn't work.
**//this query is working, I hava a doc Id**
final CollectionReference _company = FirebaseFirestore.instance
.collection('Company')
..where(FieldPath.documentId, isEqualTo: _auth.currentUser!.uid);
**// But this query is not working, because I have not doc** ID, its doc ID auto gen. ID in firebase
final CollectionReference _companyAdvert =
FirebaseFirestore.instance.collection('CompanyAdvert')..where('userId', isEqualTo: _auth.currentUser!.uid) ;
all the code here
To update a document field in firestore, you need to write
await FirebaseFirestore.instance
.collection('CompanyAdvert')
.doc(id)
.update({ 'profileImage': *new profile image* });
You must understand that to update a firestore document, you must keep a reference of the document id in the document itself. You can think of this as the primary key for the document.
There are two ways to do this.
1. Get a reference to the newly created document, and then get the id from the reference.
Then update the document with this id
2. Generate a random id locally and use that as the document id.
You can do this with the [Uuid package][1] on pub.dev
The first step goes like this:
// first, create a document using the add method
DocumentReference docRef = await FirebaseFirestore.instance
.collection('CompanyAdvert')
.add(*data*);
// then extract the generated document id
String id = docRef.id;
// then save it back to the document using
await FirebaseFirestore.instance
.collection('CompanyAdvert')
.doc(id)
.update({'id': id});
The second step goes like this:
String id = const Uuid().v4();
await FirebaseFirestore.instance.collection('CompanyAdvert').doc(id).set(*data*);
// Make sure you add the id as one of the fields to the map data
Note that the first step incurs a write operation which will count against your total quota for firebase. I recommend you use the second approach
Visit the FlutterFire documentation to learn more
I am trying to retrieve data of all the users of the users collection and compare it with some other data. I am able to retrieve data of a particular user from its uid but want to iterate through all the collections and documents.
If you don't specify a specific document ID and use the get() method on a CollectionReference, it'll return a QuerySnapshot (containing all documents in that collection) which essentially is an array of QueryDocumentSnapshot.
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["field_name"]);
});
});
You can use "QuerySnapshot" to retrieve data of all the users of the users collection. Please see an example of same at https://firebase.flutter.dev/docs/firestore/usage/#document--query-snapshots
I expect you are currently using "DocumentSnapshot" to retrieve data of a particular user.
In the 1st screen shot there are many documents in collection users. Each documents contains further collection jobPost and that collection contains further documents and its meta data.
What I want here is go to the every document of collection users and further subcollection jobPost and fetch all the documents.
Suppose first it should go to document 1 in collection users, in the document 1 it should fetch all the documnets in subcollection jobPost then it should go to the 2nd document of collection users and then get all the documents in the subcollection jobPost and so on. what will be the query or implementation to this technique
What you're describing is known as a collection group query, which allows you to query all collections with a specific name. Unlike what the name suggests, you can actually read all documents from all subcollections named jobPost that way with:
FirebaseFirestore.instance.collectionGroup('jobPost').get()...
When performing a query, Firestore returns either a QuerySnapshot or a DocumentSnapshot.
A QuerySnapshot is returned from a collection query and allows you to inspect the collection.
To access the documents within a QuerySnapshot, call the docs property, which returns a List containing DocumentSnapshot classes.
But subcollection data are not included in document snapshots because Firestore queries are shallow. You have to make a new query using the subcollection name to get subcollection data.
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
FirebaseFirestore.instance
.document(doc.id)
.collection("jobPost")
.get()
.then(...);
});
});
**
if you not have field in first collection document then its shows italic thats means its delte by default otherwise if you have field in first collection document then you can access it easily so this is the best way that i share
**
static Future<List<PostSrc>> getAllFeedPosts()async
{
List<PostSrc> allPosts = [];
var query= await FirebaseFirestore.instance.collection("posts").get();
for(var userdoc in query.docs)
{
QuerySnapshot feed = await FirebaseFirestore.instance.collection("posts")
.doc(userdoc.id).collection("userPosts").get();
for (var postDoc in feed.docs ) {
PostSrc post = PostSrc.fromDoc(postDoc);
allPosts.add(post);
}
}
return allPosts;
}
I have a question regarding a request to retrieve data from Google Cloud Firestore with specific parameters in my Flutter project.
I use the following code to check if a string in Firebase equals to a search query performed by a user:
var snapshot = await firestoreInstance.collection('categories/subcategory/items')
.where("parameter", isEqualTo: searchQuery).get()
This works if the user types exactly the name of the parameter stored in Firestore. But what I want is that it also works if only part of the searchQuery string is stored in the Firestore parameter.
I found a solution on https://medium.com/flutterdevs/implement-searching-with-firebase-firestore-flutter-de7ebd53c8c9 for this. In the article an array is created with all possibile searches for the parameter. But I think that is a bit complex and you have to generate a lot of new data in Firestore just to search for the article.
Is there a way to do this in an easier way so that you can use an operator as "contains" instead of "isEqualTo" in Flutter with Firebase for the request?
var snapshot = await firestoreInstance
.collection('categories/subcategory/items')
.where(
'parameter',
isGreaterThanOrEqualTo: searchQuery,
isLessThan: searchQuery + 'z'
)
.get();
Try this:
var snapshot = await firestoreInstance
.collection('categories/subcategory/items')
.where(
'parameter',
isGreaterThanOrEqualTo: searchQuery,
isLessThan: searchQuery.substring(0, searchQuery.length - 1) +
String.fromCharCode(searchQuery.codeUnitAt(searchQuery.length - 1) + 1),
)
.get();
I based the variable names on your example.
Here is my firestore strcuture. i want to get 'RecodeBook' collections's document id's to a List in dart.
i looked everywhere for a solution here. but i could not find.
here is the image link of firestore
Use getDocuments() method, you'll end up with querysnapshot. Get DocumentSnapshot with .documents. Print their documentId in a loop.
QuerySnapshot querySnapshot = await Firestore.instance.collection("RecodeBook").getDocuments();
var list = querySnapshot.documents;
list.forEach((f) {
print(f.documentID);
});