Cloud Firestore中自定义对象下的字段的值为空.如何避免这种情况? [英] Fields under custom object in Cloud Firestore have null value. How to avoid this?

查看:22
本文介绍了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 ,则数据库中根本不存在该字段.

If I use the constructor with two arguments, both fields are correctly populated. If I use the constructor with only one argument, only first field is populated and the second has the value of null. In Firebase Realtime database, if a field has the value of null, it's not present at all in the database.

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

What can be done to exclude the fields with null values to be added in Cloud Firestore? If there is no way, the presence of these values are affecting the database somehow?

这是我的文档的样子:

推荐答案

如果要确保在将文档写入Firestore时永远不存在null值,则可以使用Map并仅将包含以下内容的字段填充到该字段中:不包含null:

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 = new HashMap<>();
String userEmail = model.getUserEmail()
if (userEmail != null) {
    map.put("userEmail", userEmail);
}
// etc for other fields...

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

这篇关于Cloud Firestore中自定义对象下的字段的值为空.如何避免这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆