How can I retrieve a subcollection in firestore with spring framework?

Viewed 340

I have a database stored on Firestore with the following structure:

-Collection
----Document
-------Subcollection
----------Documents with Data
----Document
-------Subcollection
----------Documents with Data
----Document
-------Subcollection
----------Documents with Data

I want to retrieve the documents located in the subcollection but I can't seem to be able to with the following code:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collectionName = "states")
public class State {

    @DocumentId
    String name;

    int num_of_listings;
    Flux<Listing> listings;
}

The code for Listing is:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collectionName = "listings")
public class Listing {

    @DocumentId
    String id;

    String description;
}

Imagine each "State" contains some "Listing"s. Each POJO is accompanied by a controller with a repository injection of type FirestoreReactiveRepository like the following:

@Repository
public interface StateRepository extends FirestoreReactiveRepository<State> {
}
@RestController
@RequestMapping("/states")
@Slf4j
@RequiredArgsConstructor
public class StateController {

    private final StateRepository stateRepository;

    @GetMapping
    private Flux<State> getAllStates() {
        return stateRepository.findAll();
    }
}

When I'm requesting all the states with getAllStates() I get a null listings field while all other fields are initialized, as expected. How can I possibly achieve the desired functionality?

@Edit: If there is a way to access the subcollection directly, it is also welcome!

2 Answers

It looks like it doesn't work because you are using a field of type Flux in your entity class.

Flux<Listing> listings;

But the project does not support collections of this type currently. Try using List<Listing> instead.

Edited:

Your entity class should look like that:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collectionName = "states")
public class State {
    
    @DocumentId
    String name;
    
    int num_of_listings;

    List<Listing> listings;
    
}

Try @DBRef(db="listings")

 @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Document(collectionName = "states")
    public class State {

        @DocumentId
        String name;

        int num_of_listings;
        @DBRef(db="listings")
        Flux<Listing> listings;
    }
Related