-
Notifications
You must be signed in to change notification settings - Fork 53
/
server.js
93 lines (80 loc) · 2.75 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
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
// https://devcenter.heroku.com/articles/mongolab
// http://todomvc.com/examples/angularjs/#/
var express = require('express'),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
// Mongoose Schema definition
Schema = new mongoose.Schema({
id : String,
title : String,
completed: Boolean
}),
Todo = mongoose.model('Todo', Schema);
/*
* I’m sharing my credential here.
* Feel free to use it while you’re learning.
* After that, create and use your own credential.
* Thanks.
*
* MONGOLAB_URI=mongodb://example:[email protected]:53312/todolist
* 'mongodb://example:[email protected]:53312/todolist'
*/
mongoose.connect(process.env.MONGOLAB_URI, function (error) {
if (error) console.error(error);
else console.log('mongo connected');
});
express()
// https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters
.use(bodyParser.json()) // support json encoded bodies
.use(bodyParser.urlencoded({ extended: true })) // support encoded bodies
.get('/api', function (req, res) {
res.json(200, {msg: 'OK' });
})
.get('/api/todos', function (req, res) {
// http://mongoosejs.com/docs/api.html#query_Query-find
Todo.find( function ( err, todos ){
res.json(200, todos);
});
})
.post('/api/todos', function (req, res) {
var todo = new Todo( req.body );
todo.id = todo._id;
// http://mongoosejs.com/docs/api.html#model_Model-save
todo.save(function (err) {
res.json(200, todo);
});
})
.del('/api/todos', function (req, res) {
// http://mongoosejs.com/docs/api.html#query_Query-remove
Todo.remove({ completed: true }, function ( err ) {
res.json(200, {msg: 'OK'});
});
})
.get('/api/todos/:id', function (req, res) {
// http://mongoosejs.com/docs/api.html#model_Model.findById
Todo.findById( req.params.id, function ( err, todo ) {
res.json(200, todo);
});
})
.put('/api/todos/:id', function (req, res) {
// http://mongoosejs.com/docs/api.html#model_Model.findById
Todo.findById( req.params.id, function ( err, todo ) {
todo.title = req.body.title;
todo.completed = req.body.completed;
// http://mongoosejs.com/docs/api.html#model_Model-save
todo.save( function ( err, todo ){
res.json(200, todo);
});
});
})
.del('/api/todos/:id', function (req, res) {
// http://mongoosejs.com/docs/api.html#model_Model.findById
Todo.findById( req.params.id, function ( err, todo ) {
// http://mongoosejs.com/docs/api.html#model_Model.remove
todo.remove( function ( err, todo ){
res.json(200, {msg: 'OK'});
});
});
})
.use(express.static(__dirname + '/'))
.listen(process.env.PORT || 5000);