Spring mongodb compass missing created data/collections

Viewed 545

I Save my data to database using spring.

   @RepositoryRestResource(collectionResourceRel = "operators", path = "operators")
public interface OperatorsRepository extends MongoRepository<Operator, String> {
}

and I have file:

main\resources\application.properties

spring.data.mongodb.uri=mongodb://admin:password@myclusterurl/test?retryWrites=true&w=majority

In my config class I use:

@Bean
CommandLineRunner commandLineRunner(OperatorsRepository operatorsRepository){operatorsRepository.save(myobjToSave);}

Everything works fine, i get data saved data using REST. But my problem is that in compass mongodb I don't see created collections and data. Why? Using mongo shell and mongo atlas is the same.

2 Answers

Declaring a bean doesn't mean it is automatically executed. If you want to create a new collection from, let's say, a JSON file from the src/main/resources (or test), then you have to trigger the call of this method somehow.

I suggest to use @PostConstruct annotation that triggers once upon the object creation. Since you want to create data using the OperatorsRepository, I'd use it at @Service class injecting that object:

@PostConstruct
void createData() {
    this.operatorsRepository.save(myobjToSave);
}

Try this

spring.data.mongodb.uri=mongodb://xxxxxxxxxxxxxxxxxxx
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

Related