Reputation: 435
In Dart, how do you retrieve the auto-generated ID within a collection's document?
I have a collection called "users" that has auto ID documents with the users details. How do you retrieve that ID?
ID eg: yyHYmbDelykMPDWXHJaV
I'm trying to get this id. When the document is first created, when user is first created, the user.uid
is stored in it's collection.
I can retrieve all the data from the users
database, which I don't want:
void getData() {
databaseReference
.collection('users')
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) => print('${f.data}'));
});
}
I can get a future reference for the current user's user.uid but that still doesn't give me the unique document ID.
Future<DocumentReference> getUserDoc() async {
final FirebaseAuth _auth = FirebaseAuth.instance;
final Firestore _firestore = Firestore.instance;
FirebaseUser user = await _auth.currentUser();
DocumentReference ref =
_firestore.collection('users').document(user.uid);
print(ref);
return ref;
}
Is it possible to search the user.uid against the database users and retrieve the ID that way?
Upvotes: 7
Views: 13983
Reputation: 2264
To get the auto generated id, you can just call the document
method on whatever collection you're trying to get a document from and the returned value will have a getter for documentID
final userDocument = usersCollection.document();
final documentID = userDocument.documentID;
You usually do this when you first want to create a document. To retrieve the documentID
after you've created it, I'd add it to the user document itself:
userDocument.setData({
documentID: documentID,
/* ... */
});
Instead of using the auto generated documentID
though, I personally use the firebase user's uid
property just because it ties it back to Firebase auth
// user is a FirebaseUser
final userDocument = usersCollection.document(user.uid);
userDocument.setData({
uid: user.uid,
// ...displayName, email, etc.
});
Upvotes: 6