我使用一组文档来识别用户组。我的目的是只用用户 ID 填充文档 ID 字段,而不在文档中填写其他无用的字段。但经过一些研究后,显然,不可能有空文档。
所以,我的问题是如何将文档中的(虚拟)字段设置为 null,根据 documentation 据称 Firestore 支持该字段。 。我正在 Android 和 Web 上进行此工作,但我认为任何平台的代码都可以。
更新:我已经确认,简单地将 null 作为 Web 中的字段就可以正常工作,但是,当我在 Android 中尝试类似的操作时,如下所示:
Map<String, Object> emptyData = new HashMap<>();
emptyData.put("nullField", null);
Android Studio 警告我:
Passing 'null' argument to parameter annotated as @NotNull
我应该继续传递 null 还是我应该做其他事情?
最佳答案
假设userId
属性是String类型,请使用以下代码来更新所有具有userId = null
的用户:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<String> list = new ArrayList<>();
for (DocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}
for (String id : list) {
rootRef.collection("Users").document(id).update("userId", null).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Username updated!");
}
});
}
}
}
});
如果您正在为您的用户使用模型类,请参阅我的回答 post 。
关于firebase - 云Firestore : How to set a field in document to null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070668/