-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
133 lines (111 loc) · 2.81 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//import the modules
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
//import the schema
const Book = require('./book.model');
//setting the database
const db = 'mongodb://localhost/bookData'
//connect the mongodb database
mongoose.connect(db);
//use body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
//retreiving the info from database
app.get('/', function (req, res) {
res.send('Happy to be here!');
});
//find all Books
app.get('/books', function (req, res) {
console.log('Getting all books!');
Book.find({})
.exec(function (err, books) {
if (err) {
res.send('error has occured');
} else {
console.log(books);
res.json(books);
}
})
})
//find one book
app.get('/books/:id', function (req, res) {
console.log('finding one book');
Book.findOne({
_id: req.params.id
})
.exec(function (err, books) {
if (err) {
console.log('error comes')
} else {
console.log(books)
res.json(books);
}
})
})
//adding the book
app.post('/book', function (req, res) {
const newBook = new Book();
newBook.title = req.body.title;
newBook.author = req.body.author;
newBook.category = req.body.category;
newBook.save(function (err, book) {
if (err) {
res.send('error adding book');
} else {
console.log(book);
res.send(book);
}
})
});
//adding the book using another way
app.post('/book2', function (req, res) {
Book.create(req.body, function (err, book) {
if (err) {
console.log('error adding the book2');
} else {
console.log(book);
res.send(book);
}
})
})
//update the book
app.put('/book/:id', function (req, res) {
Book.findOneAndUpdate({
_id: req.params.id
}, {
$set: {
title: req.body.title
}
}, {
upsert: true
},
function (err, newBook) {
if (err) {
console.log('error updating book');
} else {
console.log(newBook);
res.status(204);
}
})
});
//remove a book
app.delete('/book/:id', function (req, res) {
Book.findOneAndRemove({
_id: req.params.id
}, function (err, book) {
if (err) {
console.log('error deleting book');
} else {
console.log(book);
res.status(204);
}
})
})
const port = 8080;
app.listen(port, function (req, res) {
console.log('app started!');
});