java - Cloud Firestore 中自定义对象下的字段具有空值。如何避免这种情况?

标签 java android firebase google-cloud-firestore

我有以下模型类:

public class UserModel {
    private String userEmail, userName;

    public UserModel() {}

    public UserModel(String userEmail) {
        this.userEmail = userEmail;
    }

    public UserModel(String userEmail, String userName) {
        this.userEmail = userEmail;
        this.userName = userName;
    }

    //setters and getters
}

如果我使用带有两个参数的构造函数,则两个字段都会正确填充。如果我使用仅带有一个参数的构造函数,则仅填充第一个字段,第二个字段的值为 null。在 Firebase Realtime 数据库中,如果某个字段的值为 null,则该字段根本不存在于数据库中。

如何排除要添加到 Cloud Firestore 中的 null 值的字段?如果没有办法,这些值的存在是否会以某种方式影响数据库?

这是我的文档的样子:

enter image description here

最佳答案

如果您想确保在将文档写入 Firestore 时永远不存在 null 值,您可以使用 Map 并仅使用不包含 null 的字段填充它:

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

FirebaseFirestore.getInstance().document(...).set(map);

关于java - Cloud Firestore 中自定义对象下的字段具有空值。如何避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48270150/

相关文章:

java - 从 byte[] 创建一个临时的 java.io.File

java - 一个java线程处理的多个任务正在延迟另一个java线程

java - 无法尝试实现从查询中获取随机结果到 Firestore

java - 是否可以在应用程序已运行的情况下从客户端生成对象/模型类

java - picasso 不显示来自 firebase 的图像

java - 在 XPath 1.0 中将整数转换为 double

android - 如何获得有关表情符号的所有信息

java - 为什么应用程序关闭并且 catch 子句没有捕获错误?

java - 在Android中存储大量静态数据

java - 阿瓦杰伊 bean : Why does it insert object with same ID instead of updating the object?