refactoring, fix todo removal from lists

This commit is contained in:
2018-05-19 21:45:12 +03:00
parent 97921d6ccc
commit 87ec0ac4d4
7 changed files with 55 additions and 8 deletions

View File

@@ -14,14 +14,22 @@ const TodoSchema = Schema({
TodoSchema.pre('save', async function () {
const list = await TodoList.findById(this.list);
list.todos.push(this.id);
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);
list.todos.splice(list.todos.indexOf(this._id), 1);
await list.save();
});
TodoSchema.methods.toJson = function () {
return {
id: this._id,
text: this.text,
list: this.list,
};
};
mongoose.model('Todo', TodoSchema);

View File

@@ -33,4 +33,14 @@ TodoListSchema.pre('remove', async function () {
});
});
TodoListSchema.methods.toJson = function () {
const todos = this.populated('todos') ? this.todos.map(todo => todo.toJson()) : this.todos;
return {
id: this._id,
name: this.name,
slug: this.slug,
todos,
};
};
mongoose.model('TodoList', TodoListSchema);