-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
56 lines (44 loc) · 1.48 KB
/
server.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
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
const app = express()
//middleware
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cors())
//database
mongoose.connect('mongodb://localhost:27017/myDB').catch((err) => console.log(err))
//DB schema and model
const postSchema = mongoose.Schema({
title: String,
description: String,
status: String,
location: String,
})
const Post = mongoose.model("Post", postSchema)
//api routes
app.get('/', (req, res) => {
res.send("Express is here")
})
app.post('/create', (req, res) => {
Post.create({
title: req.body.title,
description: req.body.description,
status: req.body.status,
location: req.body.location,
})
.then((doc) => console.log(doc))
.catch((err) => console.log(err))
})
app.get('/posts', (req, res) => {
Post.find().then((items) => res.json(items)).catch((err) => console.log(err))
})
app.delete('/delete/:id', (req, res) => {
Post.findByIdAndDelete({ _id: req.params.id }).then(doc => console.log(doc)).catch(err => console.log(err))
})
app.put('/update/:id', (req, res) => {
Post.findByIdAndUpdate({ _id: req.params.id }, { title: req.body.title, description: req.body.description, status: req.body.status, location: req.body.location }).then(doc => console.log(doc)).catch(err => console.log(err))
})
app.listen(3001, function () {
console.log("Server is running")
})