Node Create MongoDB Connection with Mongoose Tutorial

MongoDB is one of the best NoSQL databases; it offers a data storage solution for modern web and mobile applications.

In this tutorial, we will learn how to connect the MongoDB database connection with the Node js application.

Creating the MongoDB database connection in Node will require some additional library. Therefore, we will use the Mongoose package to connect the node app to MongoDB.

Mongoose delivers a straightforward, schema-based solution to model your application data. It possesses built-in type casting, validation, query building, and business logic hooks.

Let us find out how to seamlessly connect Mongoose + MongoDB in Node environment.

How to Connect to MongoDB Database in Node Js using Mongoose

  • Step 1: Create Project Folder
  • Step 2: Generate Package JSON
  • Step 3: Install Node Packages
  • Step 4: Build MongoDB Connection
  • Step 5: Configure Server File
  • Step 6: Check Database Connection

Create Project Folder

Open the command prompt, then type the given command and hit enter to formulate the new project folder.

mkdir node-mongo

Immediately after get into the project folder.

cd node-mongo

Generate Package JSON

In this step, we will be running the given command, this command will generate the project specific package.json file.

npm init

After executing the above command package.json file will be created in your app folder.

Install Node Packages

Next up, install the mongoose, express and body-parser packages.

npm install express mongoose body-parser

While developing the node app, it is very much obvious there will be tons of changes taking place in the project file.

Restarting the node server all over again becomes a headache.

We can tackle this problem by using the nodemon module, hence install the package by using the given command.

npm install nodemon --save-dev

Build MongoDB Connection

Mongoose offers connect method; the nodedemodb is the database name.

useNewUrlParser: The useNewUrlParser is being set to true; this flag allows users to fall back to the old parser if they find a bug in the new parser.

mongoose.connect('mongodb://0.0.0.0:27017/nodedemodb', {
  useNewUrlParser: 'true',
})

mongoose.connection.on('error', (err) => {
  console.log('err', err)
})

mongoose.connection.on('connected', (err, res) => {
  console.log('Mongoose connected successfully')
})

Configure Server File

Next, create the server.js file inside your project directory.

After building the file, make sure to register it inside the package.json as given below.

{
  "main": "server.js",
}

Now, you need to head over to server.js file and in this file you have to append the given code:

const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')

const app = express()

mongoose.connect('mongodb://0.0.0.0:27017/nodedemodb', {
  useNewUrlParser: 'true',
})

mongoose.connection.on('error', (err) => {
  console.log('err', err)
})

mongoose.connection.on('connected', (err, res) => {
  console.log('Mongoose connected successfully')
})

const PORT = 8888

app.listen(PORT, () => {
  console.log(`App is serving on PORT : ${PORT}`)
})

Check Database Connection

In the final step, we need to verify whether the app is working, and mongodb database is connected with node app and working accordingly.

Therefore we have to run the following command:

nodemon

When the database connection in node is established you will see the given message on the terminal screen.

[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`

App is serving on PORT : 8888
Mongoose connected successfully

Node Create MongoDB Connection with Mongoose Tutorial

Summary

In this quick node js MongoDB tutorial, we have comprehended how to build a MongoDB database connection in the node js application using the Mongoose client.

In this guide, we went through step by step to identify smaller problems and literally connected the node app to MongoDB with the help of the Mongoose module.