简体   繁体   中英

Firestore Java Insert documents into a collection

I am creating a following system with Firestore using the following schema:

 --- following (collection)
   |      |
   |      --- uid (document)
   |           |
   |           --- userFollowing (collection)
   |                 |
   |                 --- uid (documents)
   |                 |
   |                 --- uid (documents)

But I can't put the documents (the user ids) in the collection. This code:

Map<String, Object> following = new HashMap<>();
                    following.put("title", uid);

                    mDocRef = fsRef.collection("following").document(fAuth.getCurrentUser().getUid()).collection("userFollowing").document(uid);
                    mDocRef.set(following).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            followornot.setText("Segui giá");
                            followornot.setBackgroundColor(Color.argb(255,198, 198, 198));
                            followornotBool = true;
                        }
                    });

produces this result in the Firestore:

在此处输入图像描述

if I try with:

        mDocRef = fsRef.collection("following").document(fAuth.getCurrentUser().getUid()).collection("userFollowing");
        mDocRef.set(following).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                followornot.setText("Segui giá");
                followornot.setBackgroundColor(Color.argb(255,198, 198, 198));
                followornotBool = true;
            }
        });

It will give me the following error:

Required type: DocumentReference 
Provided: CollectionReference

so I can't do it

Is there a way to get the data structure I wrote at the beginning of the post?

You are getting the following error:

Required type: DocumentReference 
Provided: CollectionReference

Because you are trying to call the "set()" method on an object of type CollectionReference, which is actually not possible. Why? Because "set()" is a method that exists within the DocumentReference class and not within the CollectionReference class, hence the error. However, add() can be used.

The problem in your code lies in the fact that you are using the same UID in both document() method calls. In the second one, you should the UID of the user you are following, not the UID of the authenticated user. So in that collection, you should add only documents of the users you follow. Only then you can call a useful following system. More info below:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM