-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
121 lines (99 loc) · 2.49 KB
/
index.js
File metadata and controls
121 lines (99 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const ejs = require('ejs');
const mongodb = require("mongodb");
const app = express();
//mongodb connect
const MongoClient = mongodb.MongoClient;
const ObjectID = require("mongodb").ObjectID;
const url = "mongodb://localhost:27017/todoapp";
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,"public")));
//view
app.set("views",path.join(__dirname,"views"));
app.set("view engine","ejs");
//connect to database
MongoClient.connect(url,(err,database) => {
if(err) {
console.log(err);
}
db = database;
Todos = db.collection("todo");
console.log("Mongodb database is connected");
});
app.get("/",(req,res) => {
Todos.find({}).toArray((err,todo) => {
if(err) {
return console.log(err);
}
console.log(todo);
res.render("index",{
todos:todo
});
});
});
app.post("/todo/add",(req,res) => {
// console.log("Submitted");
const todo = {
text:req.body.text,
body:req.body.body
}
//insert todo
Todos.insert(todo,(err,result) => {
if(err) {
return console.log(err);
}
console.log("Todo added....");
res.redirect("/");
});
});
app.delete("/todo/delete/:id",(req,res) => {
const query = {
_id:ObjectID(req.params.id)
}
Todos.deleteOne(query,(err,response) => {
if(err) {
return console.log(err);
}
console.log("Todo removed");
res.send(200);
});
});
app.get("/todo/edit/:id",(req,res) => {
const query = {
_id:ObjectID(req.params.id)
}
Todos.find(query).next((err,todo) => {
if(err) {
return console.log(err);
}
console.log(todo);
res.render("edit",{
todo:todo
});
});
});
app.post("/todo/edit/:id",(req,res) => {
const query = {
_id:ObjectID(req.params.id)
}
// console.log("Submitted");
const todo = {
text:req.body.text,
body:req.body.body
}
//insert todo
Todos.updateOne(query,{$set:todo},(err,result) => {
if(err) {
return console.log(err);
}
console.log("Todo updated....");
res.redirect("/");
});
});
app.listen(3000,() => {
console.log("Server is running at port no 3000");
});