Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.
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.
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.
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-mongodbpackage.json inside the folder nodejs-app-with-mongodbnpm init -ymongodb to connect the MongoDB database with the nodejs application and manage data.npm install mongodb --savemongod --dbpath 'C:\Program Files\MongoDB\data\db'C:\Program Files\MongoDB\data\db to the mongoDB database and start the MongoDB server on the local system.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))node server.js and connect to the MongoDB database.$ node server.js
Connection EstablisheddisconnectServer.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))close() method to disconnect the database from the nodejs application.node disconnectServer.js and We will see the following output as shown below$ node server.js
Connected!
Ending Connection...First, We will install the npm packages listed below:
nodemon as a dev dependency.npm install nodemon --save-devnpm install express --savenpm install mongoose --savereq.body. We will run the following command to install body-parser.npm install body-parser --saveWe will arrange the folders and files as shown below:
nodejs-app-with-mongodb/
├─ public/
│ ├─ index.html
├─ index.js
├─ package.json
├─ server.js
└─ disconnectServer.jspackage.json file and add new property start to scripts object."scripts": {
"start": "nodemon index.js",
}index.js file as shown below:const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')listen() method to start the express app on local port 4000 and add the code to the index.js file as shown belowconst app = express()
app.listen(4000, (res) => {
console.log('Listening on port 4000')
})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>action attribute helps to fetch data from /student route. method attribute tells about which kind of HTTP request is performed.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,
}),
)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.connect() method.mongoose.connect('mongodb://localhost:27017/students')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)post() method of the express app to serve the HTTP request POST to the /student route.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
}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))
})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
}
]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))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))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))deleteOne() method.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).const npmPackage = {
uid: '',
npmPackage: '',
homePageURL: '',
repositoryURL: '',
}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)mongodb.MongoClient() and connect with the database using connect() method.Schema() method of Mongoose, and create a model using the model() method of Mongoose.