Category / Section
How to update MongoDB for CRUD operations in Gantt using Node.js?
5 mins read
This article explains how to update MongoDB for CRUD operations in Gantt. By using Node.js, every CRUD action in Gantt can be communicated to MongoDB. We will discuss here how to read data from the server to the Gantt component and pass edited data values from Gantt to the server to update in the MongoDB database.
Create a table in MongoDB.
Create a file in the file explorer with a preferred name (e.g., create_table.js). Run “node create_table.js” in a terminal or command prompt to create a table in MongoDB with data from a previously created file.
The sample below shows how to create a table in MongoDB.
[create_table.js]
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/', function (err, db) {
if (err) throw err;
var dbo = db.db("GanttDB");
var myobj = [
{ "TaskID": 1, "TaskName": "Parent Task 1", "StartDate": new Date("02/23/2017"), "EndDate": new Date("02/27/2017"), "Progress": "40" },
{ "TaskID": 2, "TaskName": "Child Task 1", "StartDate": new Date("02/23/2017"), "EndDate": new Date("02/27/2017"), "Progress": "40", "parentID": 1 },
{ "TaskID": 3, "TaskName": "Child Task 2", "StartDate": new Date("02/23/2017"), "EndDate": new Date("02/27/2017"), "Progress": "40", "parentID": 1 },
{ "TaskID": 4, "TaskName": "Child Task 3", "StartDate": new Date("02/23/2017"), "EndDate": new Date("02/27/2017"), "Duration": 5, "Progress": "40", "parentID": 1 },
{ "TaskID": 5, "TaskName": "Parent Task 2", "StartDate": new Date("03/14/2017"), "EndDate": new Date("03/18/2017"), "Progress": "40" },
{ "TaskID": 6, "TaskName": "Child Task 1", "StartDate": new Date("03/02/2017"), "EndDate": new Date("03/06/2017"), "Progress": "40", "parentID": 5 },
{ "TaskID": 7, "TaskName": "Child Task 2", "StartDate": new Date("03/02/2017"), "EndDate": new Date("03/06/2017"), "Progress": "40", "parentID": 5 },
{ "TaskID": 8, "TaskName": "Child Task 3", "StartDate": new Date("03/02/2017"), "EndDate": new Date("03/06/2017"), "Progress": "40", "parentID": 5 },
{ "TaskID": 9, "TaskName": "Child Task 4", "StartDate": new Date("03/02/2017"), "EndDate": new Date("03/06/2017"), "Progress": "40", "parentID": 5 }
];
dbo.createCollection("gantt", function (err, res) {
if (err) throw err;
console.log("Collection created!");
});
dbo.collection("gantt").insertMany(myobj, function (err, res) {
if (err) throw err;
console.log("data added");
});});
Create server page
Create a file named server.js or any name. In this sample, all the CRUD operations are performed (GET, POST, PUT, and DELETE).
[server.js]
var MongoClient = require('mongodb').MongoClient;
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
var cors = require('cors');
var url = "mongodb://localhost:27017/";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.listen(3001, function () {
console.log('listening on 3001')
})
app.use(cors());
app.use(express.static(__dirname))
MongoClient.connect(url)
.then(client => {
app.post("/GetData", (req, res) => {
var dbo = client.db("GanttDB");
console.log("Database created!");
app.use(function (req, res, next) {
res.header("Content-Type", "application/json");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
next();
});
dbo.collection('gantt').find({}).toArray((err, cus) => {
e = {};
e.count = 15;
e.result = cus;
res.send(e);
});
});
app.post("/BatchData", (req, res) => {
var dbo = client.db("GanttDB");
var ganttData = [];
if (req.body.added && req.body.added.length > 0) {
ganttData = req.body.added;
for (var i = 0; i < ganttData.length; i++) {
dbo.collection('gantt').insertOne(ganttData[i]);
console.log("data inserted");
}
}
if (req.body.changed && req.body.changed.length > 0) {
ganttData = req.body.changed;
for (var i = 0; i < ganttData.length; i++) {
delete ganttData[i]._id;
dbo.collection('gantt').replaceOne({ "TaskID": ganttData[i].TaskID }, ganttData[i]);
console.log("data updated");
}
}
if (req.body.deleted && req.body.deleted.length > 0) {
ganttData = req.body.deleted;
for (var i = 0; i < ganttData.length; i++) {
dbo.collection('gantt').deleteOne({ "TaskID": ganttData[i].TaskID });
console.log("data deleted");
}
}
res.send(req.body);
});
});
Initializing Gantt with MongoDB:
In Gantt, we can fetch data from a MongoDB database using the Node Entity Data Model and update the changes on CRUD actions to the server by using DataManager support. To communicate with the remote data, we are using the UrlAdaptor of the DataManager property to call the server method and get back the resultant data in JSON format.
We can define the data source for Gantt as an instance of DataManager using the url property of DataManager. Please check the below code snippet to assign the data source to Gantt.
We can define the data source for Gantt as an instance of DataManager using the url property of DataManager. Please check the below code snippet to assign the data source to Gantt.
[index.html]
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Essential JS 2 Gantt</title>
<!-- Essential JS 2 all material theme -->
<link href="https://cdn.syncfusion.com/ej2/20.2.43/material.css" rel="stylesheet" type="text/css"/>
<!-- Essential JS 2 all script -->
<script src="./scripts/ej2.js" type="text/javascript"></script>
</head>
<body>
<!-- Add the HTML <div> element for Gantt -->
<div id="Gantt"></div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
[index.js]
var data = new ej.data.DataManager({
url: 'http://localhost:3001/GetData',
batchUrl: 'http://localhost:3001/BatchData',
adaptor: new ej.data.UrlAdaptor,
crossDomain: true
});
var ganttChart = new ej.gantt.Gantt({
dataSource:data,
height: '450px',
taskFields: {
id: 'TaskID',
name: 'TaskName',
startDate: 'StartDate',
endDate: 'EndDate',
progress: 'Progress',
parentID: 'parentID'
},
toolbar: ['Add', 'Edit', 'Update', 'Delete', 'Cancel', 'ExpandAll', 'CollapseAll', 'Search'],
editSettings: {
allowEditing: true,
allowAdding: true,
allowDeleting: true,
mode: 'Auto',
},
});
ganttChart.appendTo('#Gantt');
Run the application:
- Start a local server or host
using "node server.js" in a terminal or command prompt.
- Run the index.html file in the
created application.
Please refer to the image below for the output:
Refer to the working sample for additional details and implementation: Sample