firebase - 云Firestore : How to set a field in document to null

标签 firebase google-cloud-platform google-cloud-firestore

我使用一组文档来识别用户组。我的目的是只用用户 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/

相关文章:

google-cloud-firestore - 如何从 Firestore 规则中的请求路径获取数据

ios - Firebase:搜索具有唯一ID的子节点

android - Firebase 无法获取最后一个插入值

swift - 在数据显示之前等待 1-2 秒从 Firebase 获取数据 (IOS)

python-3.x - 如何使用谷歌云函数来安排与 python 3.6 一起使用的 python 脚本?

google-cloud-platform - Google Cloud Vision API - TEXT_DETECTION

java - 如何正确显示 Cloud Firestore 列表的日期?

google-cloud-platform - 如何在不停止运行应用程序的情况下垂直扩展Google Cloud实例

Javascript/Firestore : Uncaught (in promise) TypeError: firebase. firestore(...).collection(...).doc(...).collection(...).set 不是函数

firebase - 查询与空字段的比较