index and create todos and lists

This commit is contained in:
2018-05-16 20:12:22 +03:00
parent fa053c63d5
commit 627e99f312
7 changed files with 92 additions and 5 deletions

32
routes/lists.js Normal file
View File

@@ -0,0 +1,32 @@
const express = require("express");
const mongoose = require("mongoose");
const router = express.Router();
const TodoList = mongoose.model("TodoList");
const asyncHelper = require("../asyncHelper");
// index
router.get(
"/",
asyncHelper(async (req, res) => {
const lists = await TodoList.find({})
.populate("todos")
.exec();
res.json(lists);
})
);
// create
router.post(
"/",
asyncHelper(async (req, res) => {
const { name } = req.body;
const newList = new TodoList({ name });
await newList.save();
res.json({ success: true });
})
);
module.exports = router;

34
routes/todos.js Normal file
View File

@@ -0,0 +1,34 @@
const express = require("express");
const mongoose = require("mongoose");
const router = express.Router();
const TodoList = mongoose.model("TodoList");
const Todo = mongoose.model("Todo");
const asyncHelper = require("../asyncHelper");
// index
router.get(
"/",
asyncHelper(async (req, res) => {
const todos = await Todo.find({}).exec();
res.json(todos);
})
);
// create
router.post(
"/",
asyncHelper(async (req, res) => {
const { text, listId } = req.body;
const list = await TodoList.findById(listId);
const todo = new Todo({ text, list: list._id });
await todo.save();
list.todos.push(todo.id);
await list.save();
res.json({ success: true });
})
);
module.exports = router;