Firebase Reference - flutter

How can I reference the collection in the document I auto-id in Firebase?
final CollectionReference _olanaklar5 = _database
.collection("Kategoriler")
.doc("Hoteller")
.collection("5_Yıldızlı")
.doc() //======> here
.collection("Olanaklar");

You can get list all document id with doc.id
List<String> _listDocId = [];
await fireStore
.collection("Kategoriler")
.doc("Hoteller")
.collection("5_Yıldızlı")
.get()
.then((QuerySnapshot querySnapshot) {
for (var doc in querySnapshot.docs) {
_listDocId.add(doc.id);
}
});
and query in list doc id
for (var id in _listDocId) {
final CollectionReference _olanaklar5 = _database
.collection("Kategoriler")
.doc("Hoteller")
.collection("5_Yıldızlı")
.doc(id)
.collection("Olanaklar");
}

If you're using Firebase auth, it's preferred to keep User's UID as doc, else you can use .where() as a query to match the fields in all documents. But as the app scales, it will be a hectic process and will consume many reads.

Related

Deleting document(s) inside a collection with documentReference

I have a collection in firebase called "community" and "events".
When an event document is created, a field "communityRef" is included as docRef to community.
I'm trying to figure a code that when a community is deleted, all events related to the community are also deleted.
building this in flutterflow using custom action
onTap on a button in UI, the code is included as one of the actions before community document is deleted.
Future deleteAllRefEvents(DocumentReference community) async {
final instance = FirebaseFirestore.instance;
final batch = instance.batch();
var collection = instance.collection('events');
var snapshots = await collection.where('communityRef', isEqualTo: DocumentReference).get();
for (var doc in snapshots.docs) {
batch.delete(doc.reference);
}
await batch.commit();
}
You are passing DocumentReference type instead of variable community
Your code should be as following
Future deleteAllRefEvents(DocumentReference community) async {
final instance = FirebaseFirestore.instance;
final batch = instance.batch();
var collection = instance.collection('events');
var snapshots = await collection.where('communityRef', isEqualTo: community).get();//Here you used DocumentReference instead of community
for (var doc in snapshots.docs) {
batch.delete(doc.reference);
}
await batch.commit();
}

How to fetch document name from Firestore

Trying to fetch a document name "abcd".
await _firestore
.collection("users")
.where("name", isEqualTo: _auth.currentUser?.uid)
.get()
.then((value) {
setState(() {
userMap = value.docs[0].data();
});
});
.uid is not providing the document "abcd". How can I get it?
Only need the name of document.
That name "abcd" is the document id in your Firestore database, if you need to access it you will need to set the document id as its name which you look in the Firestore database :
await _firestore
.collection("users")
.doc("abcd")
.get() ; // this will get you the abcd document
and if you want to query your collection based on uid, and get the document information from it, first you will need a field called "name" which it's value id the user's uid, then :
await _firestore
.collection("users")
.where("name", isEqualTo: _auth.currentUser?.uid)
.get(querySnapshot).then(() {
final document = querySnapshot.docs.first;
print(document.id); // this will print abcd
});

How to use Array contains in the same array fields in firebase for flutter

I have a chat collection.
each document has an array with two user id's.
my goal is to get the chat that has both user sys id's
I tried running the following but I got an error because we cant use two 'arrayContains' in one query.
Is there any way to perform such query?
here is an image of the data structure
Future getChat({required List userIdsArr}) async {
var docId = '';
userIdsArr.sort((a, b) {
return a.compareTo(b);
});
var filter1 = userIdsArr[0];
var filter2 = userIdsArr[1];
await chat
.where(userIdsArrayColumn, arrayContains: userIdsArr[0])
.where(userIdsArrayColumn, arrayContains: userIdsArr[1])
.get()
.then((value) {
value.docs.forEach((element) {
docId = element.id;
});
});
return docId;
}
the goal is to get the chat that pertains to the users being passed in userIdsArr
this seems to work, is there a better way of doing this?
Future getChat({required List userIdsArr}) async {
var docId = '';
userIdsArr.sort((a, b) {
return a.compareTo(b);
});
await chat
.where(userIdsArrayColumn, arrayContains: userIdsArr[0])
// .where(userIdsArrayColumn, arrayContains: userIdsArr[1])
.get()
.then((value) {
value.docs.forEach((element) {
if (element[userIdsArrayColumn].contains(userIdsArr[1])) {
log('match found!');
docId = element.id;
}
});
});
return docId;
}
A query can only contain a single array-contains query.
To allow your query, you'll want to add an additional field to the document where you keep the pair of UIDs in a predictable (e.g. alphabetical) order. With such a field you can then use a query such as:
where("concatenated_uids", isEqualTo: userIdsArr[0]+"_"+ userIdsArr[1])

How to read Firestore field value in flutter?

I want to get field value.
my code is..
void _checkNumner(String number) async {
final userRef = firestore.collection('users');
var documentSnapshot =
await userRef.where("number", isEqualTo: true).get().then((num) {
QuerySnapshot<Map<String, dynamic>> number = num;
print(number);
print("test");
});
print(documentSnapshot);
}
but my console is
how I get field number?
I want to load number values ​​in all docs.
I'm so beginer. T.T
Please reply from the masters
Thank you
Firebase firestore is a NoSQL, document-oriented database. User Data is stored in documents which are organized into collection , i.e collection contains list of document. In simpler words we can say QuerySnapshot contains/provide group of DocumentSnapshot. more about firestore data model
Collection --> QuerySnapshot --> Group of DocumentSnapshot
Document --> DocumentSnapshot
1) Fetch from collection - QuerySnapshot
Here we'll get list of DocumentSnapshots, we can filter by using where commad
Future<void> checkNumber(int number) async {
final QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('users')
.where("number", isEqualTo: number)
.get();
snapshot.docs.isEmpty
? {
//TODO: your code here
debugPrint("no data found")
}
: {
for (DocumentSnapshot element in snapshot.docs)
{
//TODO: your code here
debugPrint("number is: ${element['number']}"),
debugPrint("name is: ${element['name']}"),
}
};
}
1) Fetch from document - DocumentSnapshot
To fetch data from document we require documentId, and we get a single documentSnapshot instead of multiple like in above way.
Future<void> checkNumberWithDocId() async {
const String docId = 'aaaa';
final DocumentSnapshot snapshot = await FirebaseFirestore.instance.collection('users').doc(docId).get();
snapshot.exists
? {
//TODO: your code here
debugPrint("no data found")
}
: {
//TODO: your code here
debugPrint("number is: ${snapshot['number']}"),
debugPrint("name is: ${snapshot['name']}"),
};
}

Get list of document I’d present inside a collection in firestore

I have a collection named requests and inside that collection I have many Document. I want to get the Id of each document present inside that collection
Firestore.instance
.collection(FirebaseCollection.user)
.where(UserCollectionField.mobile, isEqualTo: mobile)
.getDocuments()
.then((snapshot) {
var id = snapshot.documents[0].documentID;
}).catchError((error) {
});
also you can make list of user id ex.
Firestore.instance
.collection(FirebaseCollection.user)
.where(UserCollectionField.mobile, isEqualTo: mobile)
.getDocuments()
.then((querySnapshot) async {
var list = querySnapshot.documents;
list.forEach((document) {
adminlist.add(document.documentID);
});
});