Quedemy
Sign In
connect-nodejs-to-mongodb

Connect Node JS to MongoDB


MongoDB is a NoSQL database for modern nodejs applications. MongoDB stores the data in documents and collections format. We will use the npm package mongodb to connect to a MongoDB database using Node JS. MongoDB is more easy to use than traditional databases and saves time.

What is MongoDB?

Consider, We create a student schema in a SQL database as shown below in the table. Now, We want to add additional details (i.e student Contact) to the student schema. But We can not directly insert a new field into the student schema. Because the new field is not defined in the student schema. Assuming, We have student schema defined in table format

+----------------+--------------+------+-----+---------+
| Field          | Type         | Null | Key | Default |
+----------------+--------------+------+-----+---------+
| id             | int          | NO   | PRI | NULL    |
| studentName    | varchar(255) | YES  |     | NULL    |
| section        | varchar(255) | YES  |     | NULL    |
+----------------+--------------+------+-----+---------+

But, MongoDB gives us the freedom to insert any additional details about students. We can update additional details in the object format. MongoDB adds student details as a document shown below:

// document 1
{
    id:'1',
    studentName:'Rakhi Singh',
    section:'A'
}

// document 2
{
    id:'2',
    studentName:'Nandi Ram',
    section:'B',
    contactNo:'+919999999999'
}

// document 3
{
    id:'3',
    studentName:'Ambi Singh',
    section:'A',
    contactNo:['+919999999999', '+919999999999'],
    address:'Delhi'
}

Therefore, MongoDB is different from relational databases. It comes in the category of NoSQL databases that uses JSON-based format to store documents. A relational database includes tables, raw, and column to collect the information. But NoSql Databases add data as collection or documents. A list of documents is called a collection and a list of stored objects is called document.

Install the MongoDB for Node.js

  • Create a folder named nodejs-app-with-mongodb and navigate to the folder nodejs-app-with-mongodb as shown below:
mkdir nodejs-app-with-mongodb
cd nodejs-app-with-mongodb
  • Start a new node project with npm that create a file package.json inside the folder nodejs-app-with-mongodb
npm init -y
  • Install the npm package mongodb to connect the MongoDB database with the nodejs application and manage data.
npm install mongodb --save

Connecting to The Local MongoDB Database

  • We will add a path for the MongoDB database where we will store data on the local system. And add the path as shown below
mongod --dbpath 'C:\Program Files\MongoDB\data\db'
  • In the above command, We add path C:\Program Files\MongoDB\data\db to the mongoDB database and start the MongoDB server on the local system.

Configuring The MongoDB Node.js Connection

  • Create a new file named server.js and add the following code to the file server.js.
const { MongoClient } = require('mongodb')

// Instance of MongoClient for mongodb
const mongoClientInstance = new MongoClient('mongodb://localhost:27017')

// Establish database connection
mongoClientInstance
	.connect()
	.then(() => console.log('Connection Established'))
	.catch((error) => console.log('Error in connection', error))
  • Run the command node server.js and connect to the MongoDB database.
$ node server.js
Connection Established

Closing The Connection

  • Create a new file named disconnectServer.js and add the following code to the file disconnectServer.js.
const { MongoClient } = require('mongodb')

// Create an Instance of MongoClient for mongodb
const mongoClientInstance = new MongoClient('mongodb://localhost:27017')

// Connect to database
mongoClientInstance
	.connect()
	.then(() => {
		console.log('Connected!')

		//Close the database connection
		console.log('Ending Connection...')
		mongoClientInstance.close()
	})
	.catch((error) => console.log('Error in connection!', error))
  • In the above code, We use close() method to disconnect the database from the nodejs application.
  • Run the command node disconnectServer.js and We will see the following output as shown below
$ node server.js
Connected!
Ending Connection...

Example

  • First, We will install the npm packages listed below:

    • Nodemon: It restarts the node application if any changes occur in the file of node applications. We will run the following command and install nodemon as a dev dependency.
    npm install nodemon --save-dev
    • Express: It is a backend nodejs framework that helps to build APIs in node js. We will run the following command to install express.
    npm install express --save
    • Mongoose: It is a Tool to define the schema, create a model, and manage database operations for MongoDB. We will run the following command to install mongoose.
    npm install mongoose --save
    • Bodyparser: It will parse the requested data from the client side that is available in req.body. We will run the following command to install body-parser.
    npm install body-parser --save
  • We will arrange the folders and files as shown below:

nodejs-app-with-mongodb/
├─ public/
│  ├─ index.html
├─ index.js
├─ package.json
├─ server.js
└─ disconnectServer.js
  • We will open package.json file and add new property start to scripts object.
"scripts": {
    "start": "nodemon index.js",
  }
  • We will import modules: express, mongoose, and body-parser in index.js file as shown below:
const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
  • We will use listen() method to start the express app on local port 4000 and add the code to the index.js file as shown below
const app = express()
app.listen(4000, (res) => {
	console.log('Listening on port 4000')
})
  • We will add the html form to index.html. We will use the html form to fetch the data from the web browser and store details in MongoDB locally.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
            "width=device-width, initial-scale=1.0">
    <title>Registration Form</title>
</head>
<body>
    <form action="/student" method="post">
        <input type="text" placeholder="Your Full Name" name="name">
        <input type="text" placeholder="Your Email Address" name="email">
        <button type="submit">Register</button>
    </form>
</body>
</html>
  • In the above code, action attribute helps to fetch data from /student route. method attribute tells about which kind of HTTP request is performed.
  • We will serve index.html file on local port 4000 and use the body-parser to parse the data fetched from html body.
app.use(express.static(`${__dirname}/public`))
app.use(bodyParser.json())
app.use(
	bodyParser.urlencoded({
		extended: true,
	}),
)
  • In the above code, We are using middlewares. use() method allows us to apply middlewares before serving the request to the web browser. We will add a path for static files with the help of static() method.
  • Now, We will establish the connection between the node js application and the mongodb database using the connect() method.
mongoose.connect('mongodb://localhost:27017/students')
  • In the above code, We pass the MongoDB URI and add a new collection named students if it is not created yet.
  • We will build studentDetails and validate the studentDetails with the help of Schema() method. We will create and export a model using the model() method to use it later in our nodejs application.
const studentDetails = new mongoose.Schema({
	name: String,
	email: String,
})
const StudentModel = mongoose.model('Student', studentDetails)
  • We will use the post() method of the express app to serve the HTTP request POST to the /student route.
  • We will use post method to handle POST request on the /student route and save the data to mongoDB database.
app.post('/student', (req, res) => {
	let student = new Student(req.body)
	student
		.save()
		.then((doc) => {
			res.send(doc)
			console.log(doc)
		})
		.catch((err) => console.log(err))
})
  • Now, We will enter the URL http://localhost:4000/ and register the student.

  • After registration, the form details will be stored in the MongoDB database and the following output will be displayed at the URL http://localhost:4000/student.

{
	"name": "xemployee",
	"email": "xemployee@example.com",
	"_id": "635a46cf9e89ce7cd5e7431f",
	"__v": 0
}
  • We will retrieve the list of students from the MongoDB database with the help of get() method.
// Get all students
app.get('/students', (req, res) => {
	Student.find({})
		.then((docs) => {
			console.log(docs)
			res.json(docs)
		})
		.catch((err) => console.log(err))
})
  • In the above code, We are fetching the details of students with the help of find() method. The following output will be displayed at the URL http://localhost:4000/students:
[
	{
		"_id": "635a4a55b9e33f7de6e09fd4",
		"name": "kbc",
		"email": "kbc@example.com",
		"__v": 0
	},
	{
		"_id": "635a4a8dc7824ca2d957b828",
		"name": "pqr",
		"email": "pqr@example.com",
		"__v": 0
	},
	{
		"_id": "635a4b2e0c33676d6d861ac6",
		"name": "hello",
		"email": "hello@example.com",
		"__v": 0
	}
]

Add Documents

const { MongoClient } = require('mongodb')

// Create an Instance of MongoClient for MongoDB
const mongoClientInstance = new MongoClient('mongodb://localhost:27017')

// Insert to database
mongoClientInstance
	.db('students')
	.collection('students')
	.insertOne({
		name: 'John',
		email: 'John@example.com',
	})
	.then((res) => {
		console.log(res)
		client.close()
	})
	.catch((err) => console.log(err))

Update/Delete Documents

const { MongoClient } = require('mongodb')

// Create Instance of MongoClient for mongodb
const mongoClientInstance = new MongoClient('mongodb://localhost:27017')

// Insert to database
mongoClientInstance
	.db('students')
	.collection('students')
	.updateOne(
		{ name: 'John' },
		{
			$set: { email: 'John12@example.com' },
		},
	)
	.then((res) => {
		console.log(res)
		client.close()
	})
	.catch((err) => console.log(err))
  • In the above code, We fetch the student with their name or email using the updateOne() method and update the details of a student using $set variable.
const { MongoClient } = require('mongodb')

// Create Instance of MongoClient for mongodb
const mongoClientInstance = new MongoClient('mongodb://localhost:27017')

// Insert to database
mongoClientInstance
	.db('students')
	.collection('students')
	.deleteOne({ name: 'John' })
	.then((res) => {
		console.log(res)
		client.close()
	})
	.catch((err) => console.log(err))
  • In the above code, We identify the student with their name or email and delete it using the deleteOne() method.

Mongoose

  • Mongoose is an ODM (Object Data Modeling) tool. We can create a schema-based model with the help of Mongoose. A schema is a layout that is followed to store data in the database. It helps us to identify whether the type of data is valid or not (i.e. objects, strings, booleans, numbers, etc).
  • Consider, We want to store the npm package in the MongoDB database. And we will use the following object:
const npmPackage = {
	uid: '',
	npmPackage: '',
	homePageURL: '',
	repositoryURL: '',
}
  • Now, we will add validation for the object npmPackage using mongoose and create a model named NpmPackage.
// Define schema and validate using mongoose
const npmPackageSchema = new mongoose.Schema({
	uid: { type: Number },
	npmPackage: { type: String },
	homePageURL: { type: String },
	repositoryURL: { type: String },
})

// Create model for schema `npmList` using mongoose
const NpmPackage = mongoose.model('NpmList', npmPackageSchema)

Conclusion

  • MongoDB is a NoSQL database that stores particular data as documents.
  • A list of documents is called a collection in MongoDB.
  • We can use the MongoDB database in node js using the npm package mongodb.
  • We can start mongodb database using MongoClient() and connect with the database using connect() method.
  • We can create a schema for the MongoDB database using the Schema() method of Mongoose, and create a model using the model() method of Mongoose.