Eren Akbulut's Blog

MongoDB Atlas Setup and Express Connection

July 6th, 2020

In this post, I'm going to explain how to create an online MongoDB database on MongoDB Atlas and write a basic connection script in express to connect that database.

First, let's go ahead and create an account on "https://www.mongodb.com/".

Then you should create a project as explained in that document "https://docs.atlas.mongodb.com/getting-started/", the only thing you need after that part is to receive your connection string, but in order to access your DB from anywhere while setting your connection credentials you can set IP zone as follow in order to allow all IP's:

mongoallowall

Required dependencies for the project will be like that one in package.json file:

{ "name": "projectname", "version": "1.0.0", "description": "projectdesc", "main": "server.js", "scripts": { "start": "node server", "server": "nodemon server" }, "author": "Eren Akbulut", "license": "MIT", "dependencies": { "config": "^3.3.1", "express": "^4.17.1", "mongoose": "^5.9.17", }, "devDependencies": { "nodemon": "^2.0.4" } }

After you install the node file with npm install command you can create a server.js file and config folder in the root directory, you should add db.js default.json files into the config folder.

After those files are ready you can add following code in those files:

server.js file

const express = require("express"); const connectDB = require("./config/db"); const app = express();

//Connect to our db finally connectDB();

const PORT = 5000;

app.listen(PORT, () => console.log(` Server is running on port ${PORT}`));

Runs code at localhost:5000.

const mongoose = require("mongoose"); const config = require("config"); const db = config.get("mongoURI");

const connectDB = async () => { try { await mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, }); console.log("Mongo DB Connected"); } catch (err) { console.error(err.message); process.exit(1); } };

module.exports = connectDB;

db.js file contains lots of boilerplate you won't need to make additional changes after setting it up like that, and the last required file is given below as package.json file,

{ "mongoURI": "yourmongodbatlasKEY", }

After everything is set you can simply run your code by running "npm run server". BTW since we add nodemon as a dev dependency you can just save and see your changes without running the code again.

mongoblogson

You can see the code for the project on the link: Source Code, but it contains a little bit more than what we explained today, the remaining parts will be also published soon.

This blog has been created by Eren Akbulut 2020