How to update MongoDB for CRUD operations in Gantt using Node.js?
By using Node.js, every CRUD actions in Gantt can be communicated to MongoDB. We will discuss here about how to read data from server to Gantt component, pass edited data values from Gantt to server to update in MongoDB database.
Create table in MongoDB
Create a file in file explorer with preferred name (eg: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 below sample 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 MongoDB database using Node Entity Data Model and update the changes on CRUD action to the server by using DataManager support. To communicate with the remote data we are using UrlAdaptor of DataManager property to call the server method and get back resultant data in JSON format.
We can define data source for Gantt as instance of DataManager using url property of DataManager. Please Check the below code snippet to assign 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 below image for output.
Check this sample for your reference.