This extensive guide will help you understand how to add data to the MongoDB database from the Node js application.
To insert the data into the MongoDB database, we will use mongoose, ejs, express-flash, express-session, body-parser, express-validator, and cors packages.
Mongoose is used to create a model for data, and it is an object modeling tool for the mongo database. We will harness the power of Mongoose in node js to insert a document or record into the mongo database.
Also, we will create a simple HTML form using bootstrap to save the data into the MongoDB database.
Bootstrap is the first choice that will help us design the HTML form; using this form, we will send doc or record to the MongoDB database from the Node js application.
Let’s check out the complete process:
How to Insert Record in MongoDB with Mongoose and Node Js
- Step 1: Set Up Node App
- Step 2: Add Essential Modules
- Step 3: Connect Node to MongoDB Database
- Step 4: Create Mongoose Schema
- Step 5: Build Routes in Node
- Step 6: Build Form for Sending Data
- Step 7: Configure Node Server
- Step 8: Invoke Node Application
Set Up Node App
By using the given command create a new project folder.
mkdir node-draft
Step into the new directory:
cd node-draft
Head over to command prompt, type the command, invoke the given command and generate the package.json file.
npm init
Add Essential Modules
Now, we are ready to install the EJS package.
npx express --view=ejs
Type the command again, hit enter to add the mongoose, express-flash, express-session, body-parser, and nodemon packages.
npm install -g express-generator
npm install
npm install mongoose express-flash express-session body-parser nodemon
Connect Node to MongoDB Database
To make the mongo database connection with node, make sure to create db.js file.
You need to insert the given code into the db.js file.
var mongoose = require('mongoose')
mongoose.connect('mongodb://0.0.0.0:27017/nodedemodb', {
useNewUrlParser: true,
})
var conn = mongoose.connection
conn.on('connected', function () {
console.log('Database successfully connected')
})
conn.on('disconnected', function () {
console.log('Database disconnected ')
})
conn.on('error', console.error.bind(console))
module.exports = conn
Create Mongoose Schema
Prepare the models/ folder; within this folder, make an empModel.js file; after that, copy the given code and insert it inside this file.
const mongoose = require("../db");
var empSchema = new mongoose.Schema({
name: String,
email: String
});
var empModel = mongoose.model('employees', empSchema);
module.exports = mongoose.model("Employees", empModel);
Build Routes in Node
This section will show you how to create routes for our node app, get inside the routes/users.js file and place the provided code into the file.
var express = require('express');
var mongoose = require('mongoose');
var empModel = require('./models/empModel');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { page_title: 'Add Employee' });
});
router.post('/store-user', function(req, res, next) {
req.assert('name', 'Name is required').notEmpty()
req.assert('email', 'Email is required').isEmail()
var errors = req.validationErrors()
if( !errors ) {
var empDetails = new empModel({
name: req.body.name,
email: req.body.email,
});
empDetails .save((err, doc) => {
if (!err)
req.flash('success', 'Data successfully inserted.');
res.redirect('/');
else {
console.log('Error occurred : ' + err);
}
});
}
else {
var errorMsg = ''
errors.forEach(function(error) {
errorMsg += error.msg + '<br>'
})
req.flash('error', errorMsg)
res.render('/', {
page_title: 'Data added',
name: req.body.name,
email: req.body.email
})
}
});
module.exports = router;
Build Form for Sending Data
Inside the views/ directory, you require to look for index.ejs file. Ensure that you added the following code into the recommended file.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Node Js Add Data to MongoDB Example</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
</head>
<body>
<div class="container mt-5">
<% if (messages.success) { %>
<p class="alert alert-success mt-4"><%- messages.success %></p>
<% } %>
<form action="store-user" method="POST">
<div class="mb-3">
<input
type="text"
class="form-control"
id="name"
placeholder="Enter name"
name="name"
/>
</div>
<div class="mb-3">
<input
type="email"
class="form-control"
id="email"
name="email"
placeholder="Enter email"
/>
</div>
<button type="submit" class="btn btn-danger">Add Record</button>
</form>
</div>
</body>
</html>
Configure Node Server
In the last section, we will configure the node server by adding the given below code into the app.js file.
var createError = require('http-errors')
var path = require('path')
var express = require('express')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var logger = require('morgan')
var flash = require('express-flash')
var session = require('express-session')
var empRoutes = require('./routes/users')
var app = express()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(logger('dev'))
app.use(express.json())
app.use(cookieParser())
app.use(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')))
app.use(
session({
secret: 'abcd123456',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 },
}),
)
app.use(flash())
app.use('/', empRoutes)
app.use(function (req, res, next) {
next(createError(404))
})
app.use(function (err, req, res, next) {
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}
res.status(err.status || 500)
res.render('error')
})
module.exports = app
Invoke Node Application
Let’s run the node application server by using the suggested command.
nodemon
Use the given url to run the app on the browser:
http://127.0.0.1:3000/users
Summary
Express is a handy Node.js web application framework that offers mighty features for web and mobile applications. In this tutorial, we looked at how to use express js to build api that can save the data into MongoDB in Node js.
Apart from this we also, learned to use how to get started in node from scratch. We looked at how to set up a basic node server, connect node app to MongoDB database and most importantly worked with ejs in node.