Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 285
Invalid_Path Avatar asked Dec 06 '25 15:12

Invalid_Path


1 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;
    
}
like image 175
Dmitry S Avatar answered Dec 08 '25 04:12

Dmitry S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!