Posted by : at

Category : mongodb   node

This tutorial aims to guide you to the process of building API’s using Node, Express and Mongodb.

What we are Building ?

An API for Listing Songs - User can perform CRUD operations - Create, Read, Update, Delete Songs and also the Categories/Genre the Songs belongs to.

This is the part-3 of the series :

So let’s get started :D

Connecting Mongodb to our Express App

Now we already got our Express App with ES6 Support. It’s time to connect our database to interact with our API. You need to Install MongoDB Compass. Once installed, start the mongod server (mongod.exe). This will open a connection on port 27017.

We will be using Mongoose ODM with Express for mongodb operations, and dotenv for saving our environment variables (security). Install the following dependencies.

npm install --save mongoose dotenv

Let’s create a config file for DB connection :


    import dotenv from 'dotenv';
    const dbConnectionURL = {
        'LOCALURL': process.env.DB_LOCALURL
    export default dbConnectionURL;

As you can see we have used process.env.DB_LOCALURL , this is the variable that we gonna be keeping secret in our .env file to get the database connection url



Next step is to tell express to connect to mongodb. So open our app.js and change the following code to :


    import createError from 'http-errors';
    import express from 'express';
    import path from 'path';
    import cookieParser from 'cookie-parser';
    import logger from 'morgan';
    // Add our mongoose and connection url
    import mongoose from 'mongoose';
    import dbConnectionURL from './config/db';
    // Routes
    import indexRouter from './routes';
    import songsRouter from './routes/songs';
    // mongoose options for connecting to mongodb
    const options = {
      useNewUrlParser: true, // Use the new URL Parser
      autoIndex: false, // Don't build Indexes
      reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect 
      reconnectInterval: 500, // Reconnect every 500ms
      poolSize: 10, // Maintain up to 10 Socket Connections
      // If not connected, return errors immediately rather than waiting for reconnect
      bufferMaxEntries: 0
    // set mongoose debugging true
    mongoose.set('debug', true);
    // mongoose connection url
    mongoose.connect(dbConnectionURL.LOCALURL, options);
    const db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', () => {
         // we're connected !
         console.log('Mongodb Connection Successful');
    // Initialize app
    const app = express();
    // View engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    app.use(express.urlencoded({ extended: false }));
    app.use(express.static(path.join(__dirname, 'public')));
    app.use('/', indexRouter);
    app.use('/songs', songsRouter);
    // catch 404 and forward to error handler
    app.use((req, res, next) => {
    // error handler
    app.use((err, req, res, next) => {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error ='env') === 'development' ? err : {};
      // render the error page
      res.status(err.status || 500);
    export default app;

Let’s now try to run the App :

npm run dev

It should work !

That’s it we have connected our MongoDB with our Express App. In the next part, we will be creating our Songs API and understand the concept of Data Modelling using Mongoose.

Don’t Forget to subscribe and drop comments below :D

Stay Tuned !