Reputation: 49
I can't seem to find a way to get the id of a specific document in a collection from cloud_firestore
Upvotes: 0
Views: 867
Reputation: 11
I solved it with adding the document id to the specific document itself. When you creating new collections and documents you can reach the document id and add it to your document like this:
DocumentReference docRef = await _fireStore.collection('${username}_user_data').add({
'friends': [],
'sent_friend_requests' : [],
'private_conversations' : [],
});
String docId = docRef.id;
await FirebaseFirestore.instance.collection('${username}_user_data').doc(docId).update(
{
'id' : docId
});
In my example, i created a document reference object when creating the collection/document. Then reaching that docrefs id and adding the id to the very document itself as a field.
When you have to reach/find that specific document id i have this code example related to code example above :
Future<String> getDocumentRef (String userDisplayName) async{
var collection = FirebaseFirestore.instance.collection('${userDisplayName}_user_data');
var querySnapshot = await collection.get();
var docRef;
for (var queryDocumentSnapshot in querySnapshot.docs) {
Map<String, dynamic> data = queryDocumentSnapshot.data();
docRef = data['id'];
}
return docRef;
}
I don't know if this is helps or not but i solved the exact problem like this. If anyone has better solution, i'll be happy to learn more!
Upvotes: 1