Node Js MongoDB update data example; In this tutorial, we will teach you how to build such functionality where you can easily update MongoDB data or database document in Node js application.
We are going to use express, mongoose, ejs (Embedded JavaScript templates) and most importantly Bootstrap 5 modules to create mongoDb database update feature in Node js.
Bootstrap is a notable UI library; we will use the Bootstrap module to create a data table. In the data table, we will fetch records from the MongoDB database and display the data records in the table.
Apart from that, we will add the data update button. Users will click on this button, will be taken to the data edit page with the help of the express routes, and update the data or document by using the express js API routes in Node js.
How to Update MongoDB Data in Node Js using Express Js, and Mongoose
- Step 1: Set Up Node Project
- Step 2: Install Node Packages
- Step 3: Build MongoDB Connection
- Step 4: Build Mongoose Schema
- Step 5: Define Express Routes
- Step 6: Set Up Server File
- Step 7: Fetch Data in Node
- Step 8: Update Data in Node
- Step 9: Run Node Application
Set Up Node Project
Type the command on the command prompt for creating the blank project folder.
mkdir node-tut
Get inside the project directory:
cd node-tut
Install Node Packages
In this step, you have to install the express module along with Embedded Javascript template.
npx express --view=ejs
There after go ahead and also install the given modules:
npm install -g express-generator
npm install
npm install mongoose express-flash express-session body-parser
Build MongoDB Connection
Let us set the mongo database connection, create db.js file at the root of your project folder.
Ensure that you have added 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
Build Mongoose Schema
Now, we have to create the models directory and create the UserModel.js file.
Next, insert the following code within the models/UserModel.js file.
var mongoose = require('mongoose')
var db = require('../db')
var userSchema = new mongoose.Schema(
{
name: String,
email: String,
},
{
collection: 'nodedemodb',
},
)
userTable = mongoose.model('users', userSchema)
module.exports = {
editUser: function (editId, callback) {
var userData = userTable.findById(editId)
userData.exec(function (err, data) {
if (err) throw err
return callback(data)
})
},
updateUser: function (setData, editId, callback) {
userData = userTable.findByIdAndUpdate(editId, setData)
userData.exec(function (err, data) {
if (err) throw err
return callback(data)
})
},
fetchData: function (callback) {
var userData = userTable.find({})
userData.exec(function (err, data) {
if (err) throw err
return callback(data)
})
},
}
Next, you need to create the controllers directory, also make the user-controller.js file. Add the following code into the file.
var UserModel = require('../models/UserModel')
module.exports = {
editUser: function (req, res) {
var empId = req.params.id
UserModel.editUser(empId, function (data) {
res.render('update', { empData: data })
})
},
updateUser: function (req, res) {
var setData = req.body
var empId = req.params.id
UserModel.updateUser(setData, empId, function (data) {
res.redirect('/users')
console.log(data.affectedRows + ' Document successfully updated')
})
},
fetchData: function (req, res) {
UserModel.fetchData(function (data) {
res.render('index', { data: data })
})
},
}
Define Express Routes
Inside the routes folder, you will see users.js route file, you have to insert the following code into the routes/users.js file.
var express = require('express')
var router = express.Router()
var userController = require('../controllers/user-controller')
router.get('/users', userController.fetchData)
router.get('/edit/:id', userController.editUser)
router.post('/update/:id', userController.updateUser)
module.exports = router
Set Up Server File
To set up the node server, you have to place the following code into the app.js file.
var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
var bodyParser = require('body-parser')
var flash = require('express-flash')
var session = require('express-session')
var routeUser = require('./routes/users')
var app = express()
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use(
session({
secret: 'zd59123456',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 },
}),
)
app.use(flash())
app.use('/', routeUser)
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')
})
app.listen(4000, function () {
console.log('App working on: 4000')
})
module.exports = app
Retrieve Data in Node
To fetch the mongo database data, we have to create the table view in views/index.ejs file using the bootstrap.
<!DOCTYPE html>
<html>
<head>
<title>Node Fetch Records from MongoDB</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<link rel="stylesheet" href="/stylesheets/style.css" />
</head>
<body>
<% if (messages.success) { %>
<div class="alert alert-success"><%- messages.success %></div>
<% } %>
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#ID</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<% if(data.length){ for(var i = 0; i < data.length; i++) {%>
<tr>
<th scope="row"><%= (i+1) %></th>
<td><%= data[i].name%></td>
<td><%= data[i].email%></td>
<td>
<a class="btn btn-danger edit" href="/edit/<%= data[i]._id%>"
>Edit</a
>
</td>
</tr>
<% } }else{ %>
<tr>
<td colspan="3">User not found</td>
</tr>
<% } %>
</tbody>
</table>
</body>
</html>
Update Data in Node
In this section, we will build the form which will update the MongoDB data. Like we used Bootstrap 5 for showing the users list in HTML table, use the bootstrap library to create the user form for editing the data.
In views folder create the update.ejs file and insert the following code into the file.
<!DOCTYPE html>
<html>
<head>
<title>MongoDB Update Data in Node Js</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<link rel="stylesheet" href="/stylesheets/style.css" />
</head>
<body>
<form action="/update/<%=empData.id %>" method="POST">
<h2 class="mb-3">MongoDB Update Data in Node Js</h2>
<div class="mb-3">
<label class="form-label">Enter Name</label>
<input
type="text"
placeholder="Name"
class="form-control"
name="name"
required
value="<%=(typeof empData!='undefined')? empData.name:''%>"
/>
</div>
<div class="mb-3">
<label class="form-label">Enter Email</label>
<input
type="email"
placeholder="Email"
class="form-control"
name="email"
required
value="<%=(typeof empData!='undefined')? empData.email:''%>"
/>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</body>
</html>
Run Node Application
To run the node app, we have to add the given command on the command prompt and press enter.
npm start
You can use the given url to see the data list and click on the edit button to update the data in mongo database via node app:
http://127.0.0.1:4000/users
Summary
In this comprehensive guide, we have explained how to update or edit the document in the MongoDB database using the mongoose client in the Node js application.
We have also learned how to create express APIs to fetch and update the data in MongoDB within the Node js environment.