Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore exclude data serialization

Tags:

I've got several properties that should not be transferred to Firestore, such as metadata ("id" or "parent"), and with Firebase Realtime database, there was the option to set them to protected and make a getter to make them accessible to the outside world but not serialize to Firebase.

With Firestore the only option to prevent a property from serialization is to create a class with a private property and extend that. But this is not really useful as the property is not even accessible from inside the class.

Can you help me find a solution to create class properties that don't serialize to Firestore? (Maybe annotations?)

Any help is greatly appreciated!

like image 379
Zhyano Avatar asked Nov 04 '17 18:11

Zhyano


2 Answers

To mark a field as excluded from the Firestore or Realtime database you can use the @Exclude annotation. For example:

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

    // ...
}

You can also use the @IgnoreExtraProperties annotation against the class to automatically ignore properties that don't map to class fields.

like image 91
Grimthorr Avatar answered Sep 18 '22 13:09

Grimthorr


For Kotlin you need to make sure that the getter is annotated with the @Exclude annotation and not just the appropriate field. You can do this by specifying the target of the annotation. For example:

data class Model(@get:Exclude val id: String)

@get specifies that the @Exclude annotation should be added to the value's getter. See Annotation Use-site Targets docs for more information.

This also works for data classes.

Credits to @mfulton26 for his answer https://stackoverflow.com/a/40117301/2739794.

like image 44
lionheart98 Avatar answered Sep 18 '22 13:09

lionheart98