I want to check that the user has not been created yet before creating a new one, if there is then create an error… I found a similar question, but I can’t remake it =(
Spring WebFlux: Emit exception upon null value in Spring Data MongoDB reactive repositories?
public Mono<CustomerDto> createCustomer(Mono<CustomerDto> dtoMono) {
//How Create Mono error???
Mono<Customer> fallback = Mono.error(new DealBoardException("Customer with email: " + dtoMono ???));
return dtoMono.map(customerConverter::convertDto) //convert from DTO to Document
.map(document -> {
customerRepository.findByEmailOrPhone(document.getEmail(), document.getPhone())
})
.switchIfEmpty() //How check such customer doesn't exists?
.map(document -> { //Filling in additional information from other services
var customerRequest = customerConverter.convertDocumentToStripe(document);
var customerStripe = customerExternalService.createCustomer(customerRequest);
document.setCustomerId(customerStripe.getId());
return document;
})
.flatMap(customerRepository::save) //Save to MongoDB
.map(customerConverter::convertDocument); //convert from Document to Dto
}
2
Answers
Add the following index declaration on the top of your
Customer
class:That will prevent duplicate entries to be inserted in the database.
You can catch your
org.springframework.dao.DuplicateKeyException
with the following construct:Ref: MongoDB Compound Indexes official documentation