Database Setup
In this blog we will be setting up our Database(MongoDb) using mongoose.
Step-1 We will be running the database server locally for the development phase, for that we need to download MongoDB Compass so that we can see the contents of the database
Step-2 After downloading MongoDb Compass just install it on our machine it's way simple :)
After installation open it and it should look like this
The base has been set, now lets go for the codes
Step-3 On the config.env
file we make another variable
MONGO_URI=mongodb://localhost:27017/ECommerce
Here the ECommerce is our database name, you can write anything in place of that but mind the naming conventions
After this your env file should have these contents
Step-4 Now lets make another file on the config
folder named database.js
. Here we will write the necessary code for connecting to the database.
Your folder structure shall look like this
Step-5 In the database.js
file we will write the following codes
const mongoose = require("mongoose");
const connectDatabase = () => {
mongoose
.connect(process.env.MONGO_URI)
.then((data) => {
console.log(`Mongodb connected with server ${data.connection.host}`);
})
.catch((err) => {
console.log(err);
});
};
module.exports = connectDatabase;
Here we are first importing mongoose which we have already installed on our project in Part-1.
Then we made a function where we are connecting to the MongoDb database
using mongoose.connect()
function which takes a The MONGO_URI
which we already made in our config.env
file.
After that we passed two callback functions .then()
& .catch()
which will be called when there is a success _or an _error connecting while connecting to the Database respectively.
After that we exported the function so that we can use it on our server.js
file
Step-6 Now in the server.js
file we import the connectDatabase()
from the database.js
file by writing the following line
const connectDatabase = require("./config/database");
Step-7 After the calling of dotenv.config()
and before the app.listen()
we call the function connectDatabase()
. By this the function will also get access to the environment variables .
Your server.js
file shall look like this
Step-8 Now we can test your server again by writing npm run dev
on the terminal. As we wrote an console.log() statement we shall see an statement Mongodb connected with server localhost
Congratulations we finished setting our Database, now we can proceed on making the Product APIs
Top comments (0)