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
| var mongoose = require('mongoose'); var express = require('express'); var bodyParser = require('body-parser'); const {ObjectID} = require('mongodb');
var app = express(); const port = process.env.PORT || 3000;
app.use(bodyParser.json());
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/TodoApp');
var Todo = mongoose.model('Todo',{ text:{ type:String, required:true, minlength:1, trim:true }, completed:{ type:Boolean, default:false }, completedAt:{ type:Number, default:null } });
app.post('/todos',(req,res)=>{
var todo = new Todo({ text:req.body.text }); todo.save().then((doc)=>{ res.send(doc); },(e)=>{ res.status(400).send(e); });
})
app.get('/todos', (req, res) => { Todo.find().then((todos) => { res.send({todos}); }, (e) => { res.status(400).send(e); }) });
app.get('/todos/:id', (req, res) => { var id = req.params.id;
if (!ObjectID.isValid(id)) { return res.status(404).send(); }
Todo.findById(id).then((todo) => { if (!todo) { return res.status(404).send(); }
res.send({todo}); }).catch((e) => { res.status(400).send(); }); });
app.listen(port,()=>{ console.log(`Start on port ${port}`); }); module.exports = { app, Todo }
|