diff --git a/playground/mongoose-queries.js b/playground/mongoose-queries.js new file mode 100644 index 0000000..43c812c --- /dev/null +++ b/playground/mongoose-queries.js @@ -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)) diff --git a/server/models/user.js b/server/models/user.js index 4397474..5c2fa34 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -8,3 +8,4 @@ var User = mongoose.model('User', { trim: true, }, }); +module.exports = {User}; diff --git a/server/server.js b/server/server.js index 8c7d4bf..0a573e2 100644 --- a/server/server.js +++ b/server/server.js @@ -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");