Cloud Firestore:如何将文档中的字段设置为null [英] Cloud Firestore: How to set a field in document to null

查看:86
本文介绍了Cloud Firestore:如何将文档中的字段设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一系列用于标识用户组的文档.我的意图是仅使用用户ID填写文档ID字段,而在文档中没有其他无用的字段.但是显然,在进行了一些研究之后,不可能有空文档.

I use a collection of documents that I use to identify user groups. My intention is to only fill in the document id field with the user id without having other useless fields in the documents. But after doing some research, apparently, it's not possible to have empty documents.

因此,我的问题是如何将文档中的(虚拟)字段设置为null,根据

So, my question is how to set a (dummy) field in a document to null, which is supposedly supported by Firestore according to the documentation. I'm working on this in both Android and Web, but I suppose code for any platform is OK.

更新:我已经确认,只需将null设置为Web中的字段就可以了,但是,当我尝试在Android中使用类似的方法时:

Update: I have confirmed that simply putting null as the field in Web works just fine, however, when I try the equivalent in Android like this:

Map<String, Object> emptyData = new HashMap<>();
emptyData.put("nullField", null);

Android Studio警告我:

Android Studio warns me:

将'null'参数传递给标注为@NotNull的参数

Passing 'null' argument to parameter annotated as @NotNull

我应该继续传递null还是应该做些其他事情?

Should I keep passing null or is there something else I should do?

推荐答案

假定userId属性的类型为String,请使用以下代码以便使用userId = null更新所有用户:

Assuming that the the userId property is of type String, please use the following code in order to update all users with the 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!");
                    }
                });
            }
        }
    }
});

如果您正在为用户使用模型类,请从此

If you are using a model class for your user, please see my answer from this post.

这篇关于Cloud Firestore:如何将文档中的字段设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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