-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
98 lines (73 loc) · 2.01 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
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const ejs = require("ejs");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.use(express.static("public"));
mongoose.connect("mongodb+srv://arjunsingh27:Test123@cluster0.0t9vaxx.mongodb.net/todoList")
.then(() => {
app.get("/", function (req, res) {
Item.find({})
.then((founditem) => {
console.log(founditem);
if (founditem.length === 0) { // Checking the length of the array
Item.insertMany(defaultcollection)
.then(() => {
res.redirect("/");
})
.catch((err) => {
console.error("Error inserting default collection:", err);
res.status(500).send("Internal Server Error");
});
} else {
res.render("index", { collection: founditem });
}
})
.catch((err) => {
console.error("Error finding items:", err);
res.status(500).send("Internal Server Error");
});
});
app.post("/delete", function (req, res) {
const checkItemId = req.body.checkbox;
checkremove(checkItemId);
async function checkremove(checkItemId) {
try {
await Item.findByIdAndDelete(checkItemId);
} catch (error) {
console.log("not deleted");
}
}
res.redirect("/");
});
app.post("/", function (req, res) {
const newitem = req.body.listItem;
const item = new Item({
name: newitem
});
item.save();
res.redirect("/");
});
const itemSchema = ({
name: String
});
const Item = mongoose.model("Item", itemSchema);
const item1 = new Item({
name: "task one "
});
const item2 = new Item({
name: "task tw0 "
});
const item3 = new Item({
name: "task Three "
});
const defaultcollection = [item1, item2, item3];
app.listen(process.env.PORT || 3000,function(req,res){
console.log("Server Started .........");
})
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
});