-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
107 lines (90 loc) · 2.29 KB
/
app.js
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
const express=require('express');
const path = require('path');
const bodyParser = require('body-parser');
//Port
const port=3000;
//Init App
const app = express();
//MongoClient
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID
const url ='mongodb://localhost:27017/todoapp';
//BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static((path.join(__dirname,'public'))));
//View Engine
app.set('views',path.join(__dirname,'views'));
app.set('view engine', 'ejs');
//Connect to mongodb
MongoClient.connect(url,(err,database)=>{
console.log('MongoDB Connected...');
if(err) throw err;
db = database.db('todoapp');
Todos = db.collection('todos');
app.listen(port,()=>{
console.log('Server is running on port'+port);
});
});
app.get('/',(req,res,next)=>{
Todos.find({}).toArray((err,todos)=>{
if(err){
return console.log(err);
}
res.render('index',{
todos:todos
});
})
})
app.post('/todo/add',(req,res,next)=>{
// create todo
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,next)=>{
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,next)=>{
const query ={_id:ObjectID(req.params.id)}
Todos.find(query).next((err,todo)=>{
if(err){
return console.log(err);
}
res.render('edit',{
todo:todo
});
})
})
app.post('/todo/edit/:id',(req,res,next)=>{
const query ={_id:ObjectID(req.params.id)}
// create todo
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('/');
});
});