Installation and Configuration

Connecting MongoDB with Node

After installing MongoDB, the next step is to establish a connection with Node.js, enabling your application to interact with the database programmatically.

  1. Initialize a Node.js Project

    If you haven't already, create a new directory for your Node.js project and initialize it with the following commands:

    mkdir my-node-project
    cd my-node-project
    npm init -y
    
  2. Install Mongoose

    Mongoose provides object modeling for Node.js applications to interact with MongoDB databases. Install it using npm:

    npm install mongoose
    

    Mongoose simplifies the interaction with MongoDB by providing a schema-based solution, allowing developers to define models with strongly-typed schemas. This enables straightforward data validation, querying, and manipulation through familiar JavaScript syntax within Node.js applications.

  3. Connecting to MongoDB

    Within your Node.js application, establish a connection to MongoDB using the Mongoose package. Place the following code in a file like db.config.js inside src/config

    require('dotenv').config()
    const mongoose = require('mongoose');
    
    mongoose.connect(process.env.MONGODB_URL,{
    	dbName : process.env.MONGODB_NAME,
    	autoCreate:true,
    	autoIndex:true
    })
    .then(()=>{
    	console.log("Db server connected succesfully");
    })
    .catch((exception)=>{
    	console.log(exception);
    	console.log("Error connection to DB server");
    	process.exit(1)		//stop your server running process
    })
    

    In the above code snippet utilizes the Mongoose library to establish a connection with a MongoDB database. Initially, it loads environment variables such as MONGODB_URL and MONGODB_NAME using dotenv. The mongoose.connect() function is then employed to connect to MongoDB using the URL specified in MONGODB_URL and specifying the database name from MONGODB_NAME through the dbName option, along with other configurable parameters

    Options

    autoCreate: true which ensures that the database is automatically created if it doesn't exist. This feature allows Mongoose to create the specified database upon connection if it is not already present.

    autoIndex: true enables automatic indexing of your MongoDB collections based on the schema definitions. Indexing improves query performance by allowing MongoDB to quickly locate data

    The mongoose.connect() function is asynchronous and returns a promise. The code utilizes .then() and .catch() to handle promise resolution and rejection respectively. Upon successful connection, it logs "Db server connected successfully". In case of an error during connection, it logs the error details and "Error connection to DB server", and then terminates the Node.js process using process.exit(1). This approach ensures robust database connectivity and appropriate error handling within the Node.js application.

Back to top