What is the best way to model a custom object for a document id in Firestore?

Say I have a Users collection, and I'm happy that their identifier is a generated FirestoreId document, something like:

Users Collection
    GENERATED_FIRESTORE_ID1:
        name: "User 1 name"
        ...: etc.
    GENERATED_FIRESTORE_ID2:
        name: "User 2 name"
         ...: etc."

and I add them and get them with a custom object (I am using Android at the moment, but the question, in my opinion, is more general). I don’t want to have an extra id field in the document, just use the method document.getId()to get the generated firestore id.

Is there a correct way to map a POJO so that it does not have a separate ID field, but when the request specified it to use the application? I do this 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.

}

User :

 for (DocumentSnapshot doc : documentSnapshots) {
     User user = doc.toObject(User.class);
     user.setId(doc.getId());
     users.add(user );
 }

, , FireStore ( ) , . , , , @Exclude, doc.toObject(MyCustomObject.class)

+5

Source: https://habr.com/ru/post/1693185/


All Articles