How to use query .document using firebase ui - firebase

I'm using this Firebase-UI
I have Users (collection), uid (document), and array for image url.
This is my Firebase schema
How to use document query so I can get specific user and get imageUrl?
Query query = FirebaseFirestore.getInstance()
.collection("users")
.document(auth.currentUser!!.uid)
Error:
None of the following functions can be called with the arguments supplied.
setQuery(Query, (snapshot: DocumentSnapshot) → Profile) defined in com.firebase.ui.firestore.FirestoreRecyclerOptions.Builder
setQuery(Query, SnapshotParser) defined in com.firebase.ui.firestore.FirestoreRecyclerOptions.Builder
setQuery(Query, Class) defined in com.firebase.ui.firestore.FirestoreRecyclerOptions.Builder
this works, but i just want to know if i can use .document
val query = FirebaseFirestore.getInstance()
.collection("users")
.whereEqualTo(FieldPath.documentId(), auth.currentUser!!.uid)

There is no way to use the following line of code:
Query query = FirebaseFirestore.getInstance()
.collection("users")
.document(auth.currentUser!!.uid)
Once because this is not the way you are declaring variables in Kotlin. And second because when calling document() function on a CollectionReference object it returns a DocumentRefence object and not a Query object.
So you can simply use:
val document = FirebaseFirestore.getInstance()
.collection("users")
.document(auth.currentUser!!.uid)
And the document object will now of type DocumentReference.

Related

How can I update value of the field of the document by userID Field without doc ID in the Firebase collection in flutter?

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

Flutter Firestore - How to get data from a Document Reference in a Document Field?

I'm building a Self-learning app with differente questions types. Right now, one of the questions have a field containing a list of DocumentReferences:
In Flutter, I have the following code:
Query<Map<String, dynamic>> questionsRef = firestore
.collection('questions')
.where('lesson_id', isEqualTo: lessonId);
await questionsRef.get().then((snapshot) {
snapshot.docs.forEach((document) {
var questionTemp;
switch (document.data()['question_type']) {
....
case 'cards':
questionTemp = CardsQuestionModel.fromJson(document.data());
break;
....
}
questionTemp.id = document.id;
questions.add(questionTemp);
});
});
Now, with "questionTemp" I can access all the fields (lesson_id,options,question_type, etc..), but when it comes to the "cards" field, how Can I access the data from that document reference?
Is there a way to tell firestore.instance to get the data from those references automatically? Or do I need to make a new call for each one? and, if so, how can I do that?
Thank you for your support in advance!
Is there a way to tell firestore.instance to get the data from those
references automatically? Or do I need to make a new call for each
one?
No there isn't any way to get these documents automatically. You need to build, for each array element, the corresponding DocumentReference and fetch the document.
To build the reference, use the doc() method
DocumentReference docRef = FirebaseFirestore.instance.doc("cards/WzU...");
and then use the get() method on this DocumentReference.
docRef
.get()
.then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print('Document exists on the database');
}
});
Concretely, you can loop over the cards Array and pass all the Futures returned by the get() method to the wait() method which "waits for multiple futures to complete and collects their results". See this SO answer for more details and also note that "the value of the returned future will be a list of all the values that were produced in the order that the futures are provided by iterating futures."

How to use FieldPath.of() in Firebase Firestore with Flutter

I'm trying to update a nested document field in Firebase Firestore, but when I use the FieldPath instance, It raises a compiler exception
Map _map = {
'name': 'vin',
'quantity': 2,
'costPrice': 12000,
};
var fieldPath = new FieldPath(['categories', 'branch']);
final CollectionReference _storeRef =
FirebaseFirestore.instance.collection('stores');
_storeRef.doc('6').update({fieldPath: _map});
How do I update a nested document Field using the Firebase FieldPath instance
The DocumentReference.update method requires a Map<String, dynamic> as it's first parameter and the reason for the compiler error is because you're trying to pass a FieldPath object instead of a String.
You can reduce the values of the FieldPath into a String and use that as the path for the update method.
Update this:
_storeRef.doc('6').update({fieldPath: _map});
to this:
_storeRef
.doc('6')
.update({'${fieldPath.components.reduce((a, b) => '$a.$b')}': _map});
This basically means the same as:
_storeRef
.doc('6')
.update({'categories.branch': _map});

Unable to get the documents after creating a query index

Code:
var querySnapshot = await Firestore //
.instance
.collection('collection')
.where('name', isEqualTo: ['foo'])
.orderBy('time')
.limit(1)
.getDocuments();
print('${querySnapshot.documents}'); // prints []
It returns empty List.
Database structure:
Index built
Indexing isn't an issue here. Given the query and document you're showing, I'd always expect it to return no results. You're using an array-contains type query on a field that isn't an array. Your name field is a string, and strings can't be matched by array-contains queries.
If you intended for name to be an array, you'll need to modify the document so that it is actually an array with the string "foo" in it.

Firebase Firstore subcollection

please how can I get all the value of my IndividualTaxData subcollection in Flutter.
First, you must get the reference to the parent document:
DocumentReference parentRef = Firestore.intances.collection('TaxData').document(taxDataId);
You can do the previous part with a direct reference to the document (like the code above) or with a query. Later, you must get the reference of the subcollection and the document that you get the information:
DocumentReference subRef = parentRef.collection('IndividualTaxData').document(individualTaxId);
And finally, get the data:
DocumentSnapshot docSnap = await subRef.get();
For you to return a simple document, you can use the following code for it.
var document = await Firestore.instance.collection('IndividualTaxData').document('<document_name>');
document.get() => then(function(document) {
print(document('character'));
// you can print other fields from your document
}
With the above code, you will reference your collection IndividualTaxData and then load it's data to a variable that you can print the values.
In case you want to retrieve all the documents from your collection, you can start using the below code.
final QuerySnapshot result = await Firestore.instance.collection('IndividualTaxData').getDocuments();
final List<DocumentSnapshot> documents = result.documents;
documents.forEach((data) => print(data));
// This print is just an example of it.
With this, you will load all your documents into a list that you iterate and print after - or that you can use with another method.
In addition to that, as future references, I would recommend you to check the following links as well.
Query a single document from Firestore in Flutter (cloud_firestore Plugin)
How to use Cloud Firestore with Flutter
Le me know if the information helped you!

Resources