How to get document id for Firestore document using kotlin data classes

I have a kotlin data class

data class Client(

    val name: String = "",
    val email: String = "",
    val phone: String ="") {
constructor():this("","","")}

I have a firestore to fill in the data in the class just fine, however I am in difficulty trying to figure out how to get the document id in the data class without setting it in the document itself. Is it possible?

+11
source share
6 answers

Yes, it is possible to get the identifier without saving it using DocumentSnapshot. I will try to give complete examples here.

I created a generic model class for storing id:

@IgnoreExtraProperties
public class Model {
    @Exclude
    public String id;

    public <T extends Model> T withId(@NonNull final String id) {
        this.id = id;
        return (T) this;
    }
}

Then you expand it using any model, you do not need to implement anything:

public class Client extends Model

, , age == 20:

clients.whereEqualTo("age", 20)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot documentSnapshot : task.getResult().getDocuments()) {
                        // here you can get the id. 
                        Client client = document.toObject(client.class).withId(document.getId());
                       // you can apply your actions...
                    }
                } else {

                }
            }
        });

EventListener, , :

clients.addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
        for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
            // here you can get the id. 
                        Client client = document.toObject(client.class).withId(document.getId());
                       // you can apply your actions...
        }
    }
});

documentSnapshot.getId()) .

@IgnoreExtraProperties

+22

@iCediCe DocumentSnapshot QuerySnapshot.

interface HasId {
    var id : String
}

inline fun <reified T : HasId> DocumentSnapshot.toObjectWithId(): T {
    return this.toObject(T::class.java)!!.also {
        it.id = this.id
    }
}

inline fun <reified T : HasId> QuerySnapshot.toObjectsWithId(): List<T> {
    return this.documents.map {
        it.toObjectWithId<T>()
    }
}

:

data class User(
    @get:Exclude
    override var id: String,
    ...
): HasId


val user = documentSnapshot.toObjectWithId<User>()
val users = querySnapshot.toObjectsWithId<User>()
+7

.

data class Client(
    val name: String = "",
    val email: String = "",
    val phone: String ="",
    @get:Exclude var id: String = "") {
constructor():this("","","")
}

@get: , , Firestore , , :

snapshot.documents.mapTo(list) {
            var obj = it.toObject(Client::class.java)
            obj.id = it.id
            obj
        }

.

+6

, QueryDocumentSnapshot :

inline fun <reified T : HasId>QueryDocumentSnapshot.toObjectWithId(): T {
    val model = this.toObject(T::class.java)
    model.id = this.id
    return  model
}

( ):
 myModelWithId = it.toObjectWithId<MyModel>()

hasId, :

interface HasId{
    var id : String
}

@IgnoreExtraProperties
data class MyModel(
        @get:Exclude override var id : String    = "",
        val data                     : String    = "",

): Serializable, HasId
+6

. , Firestore , .

:

@DocumentId val documentId: String

Firestore toObject toObjects. .set() Firestore, .

+1

Firestore , Firebase:

    override fun addTodo(todo: Todo) =
    Completable.fromAction {
        val id = firestore
            .collection(COLLECTION_TODOS)
            .document()
            .id

        val newTodo = todo.copy(id = id)

        firestore
            .collection(COLLECTION_TODOS)
            .document(id)
            .set(newTodo)
    }
0

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


All Articles