-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver-express.js
49 lines (41 loc) · 1023 Bytes
/
server-express.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
const express = require('express');
const mongoose = require('mongoose');
const mongooseErrorHandler = require('../');
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost/example', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const schema = new mongoose.Schema({
name: {
type: String,
required: true,
},
});
const model = mongoose.model('person', schema);
const app = express();
app.use(express.json());
app.post('/', async (req, res, next) => {
try {
const object = await model.create(req.body);
res.json(object);
} catch (error) {
next(error)
}
});
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use((err, req, res) => {
let error = mongooseErrorHandler(err);
if (error.name === 'MongooseValidatorError') {
error.status = 400;
}
res.status(error.status || 500);
res.json({ message: error.message });
});
app.listen(3000)