DEV Community

Ado Kukic for DigitalOcean

Posted on

How to Easily Connect to DigitalOcean's Managed MongoDB

So you've just created a new MongoDB database using DigitalOcean's managed databases and you're wondering how to connect it to your application. Whether you're building a new app, adding new features to an existing one, or just want to access your newly created database cluster, it has never been easier to connect to your MongoDB database on DigitalOcean.

Simply copy the connection string provided in the Connection Details section of the dashboard and remember to replace the password field with your password and you're off to the races.

Connection String

If you forgot or don't have your password on hand, you can generate a new one in the Users and Databases tab by clicking on the More Options menu and hitting the Reset Password button. You'll need to provide your username and then you will be able to reveal the newly generated password.

Reset password

Make a note of your password as you need it in just a little bit. Let's connect our MongoDB database to the official MongoDB GUI tool, MongoDB Compass. I'll open up Compass and in the new connection card I'll add my connection string, add the password and hit Connect. If all is right, I'll be connected and can view, edit, and manipulate data in my MongoDB database.

MongoDB Compass

The same process of connecting can be applied to our applications. I have a simple NodeJS application that is going to connect to our database cluster using the MongoDB NodeJS driver and will write some data to a database called test in a file called index.js.

const { MongoClient } = require("mongodb");

let client = new MongoClient("mongodb+srv://doadmin:{REPLACE-WITH-YOUR-PASSWORD}", {
  useNewUrlParser: true,
  useUnifiedTopology: true,

client.connect().then((client) => {
  db = client.db("test");

  db.collection("test").insertOne({ message:"Hello from DigitalOcean!"}).then(()=>{

Enter fullscreen mode Exit fullscreen mode

Just like with the Compass example, we just need to provide the connection string and we'll be good to go. Let's see it in action.

To run the app, from your terminal window execute the following command: node index.js. The app will connect to MongoDB, insert a document in the test collection, inside of a database called test, and then exit.

Going back to Compass and refreshing our database, we can see the newly added data. That's it! Now that you know how to connect your DigitalOcean MongoDB cluster to your applications, I can't wait to see what you will build.

MongoDB Compass data

Good luck, luck and happy coding.

You can watch a video walkthrough of the above tutorial below:

Top comments (0)