Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (85 loc) · 2.29 KB
/
Copy pathindex.js
File metadata and controls
92 lines (85 loc) · 2.29 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
const express = require("express");
const app = express();
const port = 8080;
const mongoose = require('mongoose');
const Chat = require('./models/chat.js');
const path = require("path")
const methodOverride = require("method-override");
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")))
app.use(express.urlencoded({extended : true}));
app.use(methodOverride("_method"));
//server connection setup
app.listen(port, () => {
console.log(`port is listening to ${port}`);
})
app.get("/", (req, res) => {
res.render("home.ejs")
})
//to read all chats
app.get("/chats", async (req, res) => {
let chats = await Chat.find();
res.render("index.ejs", { chats });
})
// to create/add new chats
app.get("/chats/new", (req, res) => {
res.render("newChat.ejs");
})
app.post("/chats", async(req, res) => {
let chat = req.body;
if(chat.from && chat.msg && chat.to){
let Chats = new Chat({
from : chat.from,
msg : chat.msg,
to : chat.to,
sent_at : new Date()
})
await Chats.save();
res.redirect("/chats")
}else {
res.send("<h1> Type Something in Empty Fields")
}
// let Chats = new Chat({
// from : chat.from,
// msg : chat.msg,
// to : chat.to,
// sent_at : new Date()
// })
// await Chats.save();
// res.redirect("/chats")
})
//to update/edit chats
app.get("/edit/:id", async(req, res) => {
let {id} = req.params;
let chat = await Chat.findById(id);
res.render("edit.ejs", { chat })
})
app.patch("/edit/:id", async (req, res) => {
let {id} = req.params;
let {msg:updatedMsg} = req.body;
await Chat.findByIdAndUpdate(id, {msg : updatedMsg});
res.redirect("/chats")
})
//to delete chats
app.get("/delete/:id", async(req, res) => {
let {id} = req.params;
let chat = await Chat.findById(id)
res.render("delete.ejs", {chat})
})
app.delete("/delete/:id", async(req, res) => {
let {id} = req.params;
await Chat.findByIdAndDelete(id)
res.redirect("/chats")
})
app.post("/delete/:id", (req, res) => {
res.redirect("/chats")
})
//mongoose connection setup
main()
.catch(e => {
console.log(e)
})
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/inbox')
}