ebm37028
ebm37028

Reputation: 13

Spring / Reactor : Retrieve and modify a Mono

I have the following model :

class Person {
    List<Address> addresses;
}

I used the ReactiveMongoRepository to retrieve a Mono.

public interface PersonRepository extends ReactiveMongoRepository<Person, String>{
}

But I can't find a way to add an Address to the person's addresses and return a Mono of the given Address. Here is the signature of what I want to achieve :

Mono<Address> addAddress(Address address)

Here is the code I used to use without Reactor :

public Mono<Addresses> addAddress(Address address){
    Mono<Person> person = personRepository.findById(personId);
    // person.getAddresses().add(address) ?
    // personRepository.save(person) ?
    // return "address" as Mono
}

Question: How can I add an Address to a Mono<Person> and then return a Mono of that Address ?

Upvotes: 0

Views: 517

Answers (1)

arap
arap

Reputation: 509

This one should do the trick:

public Mono<Addresses> addAddress(Address address){
        return personRepository.findById(personId)
                .doOnNext(p -> p.getAddresses().add(address))
                .flatMap(personRepository::save)
                .then(Mono.just(address));
}

then() waits for repository to save data, and after it completes, returns the address.

Another way is to extract (map) address from person returned by repository (it might be better solution, if address gets modified durning saving process)

public Mono<Addresses> addAddress(Address address){
        return personRepository.findById(personId)
                .doOnNext(p -> p.getAddresses().add(address))
                .flatMap(personRepository::save)
                .map(savedPerson -> savedPerson.getAddressess().findThisParticularJustSavedOne());
}

Upvotes: 1

Related Questions