add GET /todos/:id

This commit is contained in:
Tyrel Souza 2017-11-30 22:18:17 -05:00
parent 3191ee36c8
commit 33b68638d3
3 changed files with 55 additions and 1 deletions

View File

@ -0,0 +1,36 @@
const {ObjectID} = require('mongodb');
const {mongoose} = require('./../server/db/mongoose');
var {Todo} = require('./../server/models/todo');
var {User} = require('./../server/models/user');
var id = "5a1f8b894489ab9c513e0c1d";
var _id = "5a1f7aaa4698bf6e30745768"
if (!ObjectID.isValid(id)){
console.log("Invalid id");
}
// Todo.find({
// _id: id,
// }).then((todos) => {
// console.log('Todos', todos);
// })
//
// Todo.findOne({
// _id: id,
// }).then((todo) => {
// console.log('Todo', todo);
// })
Todo.findById(id).then((todo) => {
if(!todo){
return console.log("id not found");
}
console.log("Todo by id:",todo);
}).catch((e) => console.log(e))
User.findById(_id).then((user) => {
if(!user){
return console.log("id not found");
}
console.log("User by id:", user);
}).catch((e) => console.log(e))

View File

@ -8,3 +8,4 @@ var User = mongoose.model('User', {
trim: true,
},
});
module.exports = {User};

View File

@ -1,5 +1,7 @@
var express = require('express')
var bodyParser = require('body-parser')
const {ObjectID} = require('mongodb');
var {mongoose} = require('./db/mongoose')
var {User} = require('./models/user')
@ -22,13 +24,28 @@ app.post('/todos', (req, res) => {
});
app.get('/todos', (req, res) => {
var todos = Todo.find().then((todos) => {
Todo.find().then((todos) => {
return res.send({todos});
}, (e) => {
return 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(req.params.id).then((todo) => {
if(!todo){
return res.status(404).send();
}
return res.send({todo});
}).catch((e) => res.status(400).send())
});
app.listen(8888, () => {
console.log("Started on port 8888");