Andrei Margeloiu
Andrei Margeloiu

Reputation: 959

How to connect to online MongoDB database from Spring Boot?

I want to connect to an online MongoDB database hosted at Mlab, from inside a Spring Boot application.

I have configured the application.properties with the URI:

spring.data.mongodb.uri = mongodb://myuser:[email protected]:29532/consilium-dev

However, the application still connects to the local MongoDB database. How can I make it connect to the Mlab database?

SOLUTION: The resources folder was not situated in the right folder. It should be in src/java/resources

Upvotes: 2

Views: 3999

Answers (2)

realpac
realpac

Reputation: 572

In my case, spring boot was connecting to the uri specified in application.properties file while testing in my PC but once deployed to heroku, it always connected to the localhost irrespective of what was specified in application.properties. Solution was to pass the database uri as command line arguments while deploying the jar to the server because this will take precedence over the properties. To do so, create a Procfile like:

web: java -Dserver.port=$PORT -Dspring.data.mongodb.uri=mongodb://<user>:<pass>@<host>:<port>/<db> -jar my-app.jar

And using heroku toolkit, run following command.

heroku deploy:jar -j my-app.jar -i Procfile --app <host-name>

Upvotes: 2

Sanjay
Sanjay

Reputation: 115

Using database values in the application.properties didn't work for me for online mongodb. It works fine for local db. But Once I google and found an example online where they added it in this way below and it worked for me.

spring.data.mongodb.uri=mongodb://<USERNAME>:<PASSWORD>@ds261828.mlab.com:61828/springdb.

Upvotes: 1

Related Questions