Todo App - Making MongoDb Database Connection
January 26th 2021 82

So now our Todo model is ready we can now move on to make database connection with the Mongodb for that we are going to use MongoDB Atlas
Now follow the steps in this blog and get the database url
which will look like this:
mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority
Now, Add below line in the .env
file, complete the database string with your password and database name
DATABASE_URL=mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority
Updated .env
.env
PORT=3000
DATABASE_URL=mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority
Making Database Connection
Open app.js
file
Import mongoose
const mongoose = require("mongoose");
Add this line below where PORT is defined:
const dbURI = process.env.DATABASE_URL;
now create a database connection
// making database object
const connect = mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// connecting with database
connect.then(
(db) => {
console.log("Connected Successfully to Mongodb Server");
},
(err) => {
console.log(err);
}
);
Update app.js
// import express
const express = require("express");
//import mongoose
const mongoose = require("mongoose");
// import dotenv
const dotenv = require("dotenv");
// load environment variable
dotenv.config({ path: ".env" });
// read env variable using process.env.<your_env_variable_name>
const PORT = process.env.PORT;
const dbURI = process.env.DATABASE_URL;
// making connection object
const connect = mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// connecting with database
connect.then(
(db) => {
console.log("Connected Successfully to Mongodb Server");
},
(err) => {
console.log(err);
}
);
// initialize express app
const app = express();
// sending a hello response on visiting http://localhost:3000/
app.get("/", (req, res) => {
res
.status(200)
.json({ message: "Hi I am Server", data: "no data on this endpoint" });
});
// listening for any HTTP requests on PORT 3000
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Restart
your server and you should see following output in your terminal:
Output:
Server is running at http://localhost:3000
Connected Successfully to Mongodb Server
Now we are successfully connected
with the database and now we can move on to create routes
and controllers,
In our next section.