-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
89 lines (78 loc) · 2.71 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
//import the dependencies
const Express = require("express");
const Mongoose = require("mongoose");
const BodyParser = require("body-parser");
var app = Express();
var port = process.env.PORT || 3000;
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
//connect to mongodb via mongoose
const mongoose = require('mongoose');
let dev_db_url = 'mongodb+srv://productuser:[email protected]/test2';
const mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// create model schema
let PersonModel = mongoose.model('person', {
firstname: String,
lastname: String
});
// function to create new documents for the created model
app.post("/person", async (request, response,next) => {
try {
var person = new PersonModel(request.body);
var result = await person.save();
response.send(result);
} catch (error) {
response.status(500).send(error);
}
});
// function to retrieve all the documents in the collection
app.get("/people", async (request, response,next) => {
try {
var result = await PersonModel.find().exec();
response.send(result);
} catch (error) {
response.status(500).send(error);
}
});
// function to retrieve a document contents with its id
app.get("/person/:id", async (request, response,next) => {
try {
var person = await PersonModel.findById(request.params.id).exec();
response.send(person);
} catch (error) {
response.status(500).send(error);
}
});
// function to update a document with its id
app.put("/person/:id", async (request, response,next) => {
try {
var person = await PersonModel.findById(request.params.id).exec();
person.set(request.body);
var result = await person.save();
response.send(result);
} catch (error) {
response.status(500).send(error);
}
});
// function to delete a document with particular id
app.delete("/person/:id", async (request, response,next) => {
try {
var result = await PersonModel.deleteOne({ _id: request.params.id }).exec();
response.send(result);
} catch (error) {
response.status(500).send(error);
}
});
app.post("/person", async (request, response) => {});
app.get("/person", async (request, response) => {});
app.get("/person/:id", async (request, response) => {});
app.put("/person/:id", async (request, response) => {});
app.delete("/person/:id", async (request, response) => {});
app.use(Express.static('public'))
app.listen(port, () => {
console.log("Listening at "+port);
});