refactoring

This commit is contained in:
2018-05-19 18:10:56 +03:00
parent c0af83f3f1
commit 8f0509b8f2
8 changed files with 668 additions and 21 deletions

View File

@@ -1,5 +1,6 @@
const mongoose = require('mongoose');
const TodoList = mongoose.model('TodoList');
const { Schema } = mongoose;
const TodoSchema = Schema({
@@ -11,4 +12,16 @@ const TodoSchema = Schema({
completed: { type: Boolean, default: false },
});
TodoSchema.pre('save', async function () {
const list = await TodoList.findById(this.list);
list.todos.push(this.id);
await list.save();
});
TodoSchema.pre('remove', async function () {
const list = await TodoList.findById(this.list);
list.todos.remove(this.id);
await list.save();
});
mongoose.model('Todo', TodoSchema);

View File

@@ -7,11 +7,11 @@ const TodoListSchema = Schema({
name: {
type: String,
required: true,
lowercase: true,
},
slug: {
type: String,
required: true,
lowercase: true,
},
todos: [{ type: Schema.Types.ObjectId, ref: 'Todo' }],
});
@@ -27,11 +27,10 @@ TodoListSchema.methods.slugify = function () {
this.slug = slugify(this.name);
};
TodoListSchema.methods.removeWithTodos = function () {
this.todos.forEach((todo) => {
todo.remove();
TodoListSchema.pre('remove', async function () {
this.todos.forEach(async (todo) => {
await todo.remove();
});
this.remove();
};
});
mongoose.model('TodoList', TodoListSchema);