-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
109 lines (89 loc) · 1.84 KB
/
app.js
File metadata and controls
109 lines (89 loc) · 1.84 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
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const dotenv = require("dotenv");
dotenv.config();
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
const url= "mongodb+srv://shubhrima:"+process.env.PASSWORD+"@cluster0.mjoba.mongodb.net/booksDB";
mongoose.connect(url, {useNewUrlParser: true, useUnifiedTopology: true});
const bookSchema = new mongoose.Schema({
title: String,
author: String,
rating: String,
});
const Book = mongoose.model('Book', bookSchema); //model
app.route('/books')
.get(
(req, res) => {
Book.find(function(err, foundBooks){
if (!err)
{
res.send(foundBooks);
}
else
{
res.send(err);
}
})
})
.post(
(req, res) => {
const newBook = new Book({
title: req.body.title,
author: req.body.author,
rating: req.body.rating,
});
newBook.save();
if (!err)
{
res.send('Successfully added');
}
else
{
res.send(err);
}
});
app.get('/books/:book', function(req,res){
var query = { 'title' : req.params.book };
Book.findOne(query, function(err, item) {
res.send(item);
});
});
app.patch('/books/:book', (req, res) => {
Book.updateOne(
{ 'title' : req.params.book },
{$set : req.body},
function(err, item)
{
if (!err)
{
res.send(item);
}
console.log(err);
});
});
app.delete('/books/:book', (req, res) => {
Book.deleteOne(
{ 'title' : req.params.book },
function(err, item)
{
if (!err)
{
res.send(item);
}
console.log(err);
});
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port,function(){
console.log("Server working fine!");
})