I’m building a taskmanagment application, where only admin can delete user. when admin delete a user, I want to assign deleted users task to the his assignby user.
JavaScript
x
10
10
1
{
2
_id: new ObjectId("63bad43ee5d01d4cc13d58b2"),
3
title: 'Test task',
4
completed: false,
5
urgent: false,
6
assignedBy: new ObjectId("63afc89d7e3da6e5d996d415"), // ex: john
7
asignTo: new ObjectId("63bac632f2f1830832d229a4"), // ex: devid
8
__v: 0
9
}
10
when I delete devid user from the db I want to assign his task to the john and save the task
JavaScript
1
10
10
1
{
2
_id: new ObjectId("63bad43ee5d01d4cc13d58b2"),
3
title: 'Test task',
4
completed: false,
5
urgent: false,
6
assignedBy: new ObjectId("63afc89d7e3da6e5d996d415"), // ex: john
7
asignTo: new ObjectId("63afc89d7e3da6e5d996d415"), // ex: john
8
__v: 0
9
}
10
Advertisement
Answer
I think you are looking for transactions to avoid loss data.
So you can try somethig like (not real code):
JavaScript
1
15
15
1
const updateAndDelete = async (userToRemove) => {
2
const session = await db.startSession()
3
try {
4
session.startTransaction();
5
const user = await User.findById(userToRemove, {session: session})
6
const {assignedBy} = user
7
await user.remove({session: session})
8
await Task.updateMany({asignTo: userToRemove}, {asignTo: assignedBy}, {session: session})
9
await session.commitTransaction();
10
} catch(e) {
11
await session.abortTransaction();
12
}
13
session.endSession();
14
}
15
If everything is ok, you commit the transaction and all changes are saved (also you can add some if
an thorw an exception if you want), otherwise you can do a rollback and there is not any data loss.