我有以下模型类:
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
值的字段?如果没有办法,这些值的存在是否会以某种方式影响数据库?
这是我的文档的样子:
最佳答案
如果您想确保在将文档写入 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/