Cloud Firestore: How to set a field in document to null

后端 未结 3 816
南笙
南笙 2021-01-24 20:00

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

3条回答
  •  太阳男子
    2021-01-24 20:37

    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() {
        @Override
        public void onComplete(@NonNull Task task) {
            if (task.isSuccessful()) {
                List 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() {
                        @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.

提交回复
热议问题