What's the best way to model Custom Object for Document ID in Firestore?

て烟熏妆下的殇ゞ 提交于 2020-07-06 10:25:30

问题


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)


回答1:


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



来源:https://stackoverflow.com/questions/48621586/whats-the-best-way-to-model-custom-object-for-document-id-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!