fix todolist removal

This commit is contained in:
2018-06-01 17:51:28 +03:00
parent 33b802d9e7
commit 9c354f5445
5 changed files with 19 additions and 6 deletions

View File

@@ -22,12 +22,20 @@ TodoListSchema.pre('save', async function () {
TodoListSchema.pre('remove', async function () {
const user = await this.model('User').findById(this.user);
user.lists.splice(user.lists.indexOf(this._id), 1);
await user.save();
// removing todos in parallel can cause VersionError
// so we remove todos from user
const todos = await this.model('Todo')
.find({ list: this._id })
.exec();
await Promise.all(todos.map(todo => todo.remove()));
const ids = todos.map(todo => todo._id);
user.todos = user.todos.filter(todo => ids.includes(todo._id));
await user.save();
// and remove them from db
await this.model('Todo')
.find({ list: this._id })
.remove()
.exec();
});
TodoListSchema.methods.toJson = function () {

View File

@@ -22,10 +22,14 @@ UserSchema.plugin(passportLocalMongoose);
UserSchema.plugin(uniqueValidator);
UserSchema.pre('remove', async function () {
const lists = await this.model('TodoList')
await this.model('TodoList')
.find({ user: this._id })
.remove()
.exec();
await this.model('Todo')
.find({ user: this._id })
.remove()
.exec();
await Promise.all(lists.map(list => list.remove()));
});
UserSchema.methods.generateJwt = function () {