8

I'm using Firebase Cloud Firestore, I want when I'm getting a document with reference field inside to receive the reference field as a document and not as a reference to the document...

I have a collection of users and collection of classes (at school) and each class contains a list of references to users (the students in this class). When I using document.get() (to get the class by its reference) it returns an object that contains a list of DocumentReference (of the users) so I need to call document.get() around 20 more times just to get the users as objects and not as a reference to them.

I want to be able to call document.get() once and it will bring me all the references as documents, like that: database and code

Is there an elegant way to do this?

Roi Amiel
  • 353
  • 1
  • 3
  • 18

2 Answers2

8

You can't instruct the Firestore client SDK to automatically follow document references during a fetch of a single document. You have to request each individual document. In other words, there is no "join" operation like you might expect in SQL.

See also: What is firestore Reference data type good for?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

You can get multiple documents from a collection. Read get mutiple documents section from documentation

Here's an example

db.collection("classes")
    .document(idOfTheClassYouWantToGet)
    .collection("users")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>(){
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (DocumentSnapshot document : task.getResult()) {
                    User user = document.toObject(Users.class);
               }
            } 
        }
    });
UdeshUK
  • 972
  • 1
  • 11
  • 19
  • in addOelsenCompleteListener you mean addOnCompleteListener? It will only return a list of document references – Roi Amiel Jan 06 '18 at 17:59
  • Yes, you can get document by calling task.getResult(). I'll edit my answer – UdeshUK Jan 06 '18 at 18:07
  • I think you didn't understand me well, this is my [database now](https://ibb.co/ee9bew) and I want to do something like [this](https://ibb.co/k0feXG) (the code is in kotlin but is the same for java) – Roi Amiel Jan 06 '18 at 18:25
  • Alright you're keeping paths to users. It isn't a vary good approch. Instead write user to database with add() function. It will create an unique id for each user. Then store that id in the class collection. So you can get users of a class using that. – UdeshUK Jan 06 '18 at 18:31
  • @RoiAmiel In case if users have only one class then write users to a sub collection in a class – UdeshUK Jan 06 '18 at 18:33