Reputation: 3302
Say I have a collection of 'Users', and am happy for their ID to be the generated Firestore documentId, something like:
Users Collection
GENERATED_FIRESTORE_ID1:
name: "User 1 name"
...: etc.
GENERATED_FIRESTORE_ID2:
name: "User 2 name"
...: etc."
and I am adding them, and retrieving them with a custom object (I'm using Android at the moment but the question I guess is more generalistic). I don't want to have an extra "id" field in the document, just use the document.getId()
method to get the generated firestore ID.
Is there a correct way to map a POJO to not have an indivual ID field, but when querying set it for application usage? I am doing it using the @Exclude annotation as follows:
public class User {
// as a side question, do I need @exclude on the field or just the getter?
@Exclude
String uId;
String name;
String email;
//... additional fields as normal
public User() {
}
@Exclude
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.displayName = name;
}
//... etc. etc.
}
and then I create the User object and set its ID as follows:
for (DocumentSnapshot doc : documentSnapshots) {
User user = doc.toObject(User.class);
user.setId(doc.getId());
users.add(user );
}
This works fine, and apologies if this is indeed the way, but I'm new to FireStore (am loving it) and want to make sure I'm doing it right. I just wondered if there was a way this would all be automatic, without @Exclude and then manually setting the ID after doc.toObject(MyCustomObject.class)
Upvotes: 12
Views: 2710
Reputation: 2529
There is now an Annotation for this -
You could simply use
@DocumentId
String uID
https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentId.html
Upvotes: 15