Skip to content Skip to sidebar Skip to footer

Fields Under Custom Object In Cloud Firestore Have Null Value. How To Avoid This?

I the have the following model class: public class UserModel { private String userEmail, userName; public UserModel() {} public UserModel(String userEmail) {

Solution 1:

If you want to make sure that there are never null values when writing a document to Firestore, you can use a Map and populate it with only the fields that do not contain null:

UserModel model = ...
HashMap<String, Object> map = newHashMap<>();
String userEmail = model.getUserEmail()
if (userEmail != null) {
    map.put("userEmail", userEmail);
}
// etc for other fields...FirebaseFirestore.getInstance().document(...).set(map);

Solution 2:

Unlike in Firebase Realtime database, where non-existing values are not displayed at all, in Cloud Firestore if you add a field which is null the result will be:

yourField:null

If you add a String with the value of "" (not value at all), the result in your database will be:

yourField:""

If you don't want to have null or "" values in your database you can create a map and use FieldValue.delete() like this:

Map<String, Object> map = new HashMap<>();
map.put("yourField", FieldValue.delete());
yourRef.update(map);

This kind of fields won't be displayed anymore.

Post a Comment for "Fields Under Custom Object In Cloud Firestore Have Null Value. How To Avoid This?"