[英]How update and delete bulk operation in mongodb?
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.当管理员删除用户时,我想将删除的用户任务分配给他的 assignby 用户。
{
_id: new ObjectId("63bad43ee5d01d4cc13d58b2"),
title: 'Test task',
completed: false,
urgent: false,
assignedBy: new ObjectId("63afc89d7e3da6e5d996d415"), // ex: john
asignTo: new ObjectId("63bac632f2f1830832d229a4"), // ex: devid
__v: 0
}
when I delete devid user from the db I want to assign his task to the john and save the task当我从数据库中删除 devid 用户时,我想将他的任务分配给 john 并保存任务
{
_id: new ObjectId("63bad43ee5d01d4cc13d58b2"),
title: 'Test task',
completed: false,
urgent: false,
assignedBy: new ObjectId("63afc89d7e3da6e5d996d415"), // ex: john
asignTo: new ObjectId("63afc89d7e3da6e5d996d415"), // ex: john
__v: 0
}
I think you are looking for transactions to avoid loss data.我认为您正在寻找交易以避免丢失数据。
So you can try somethig like (not real code):所以你可以尝试一些类似的东西(不是真正的代码):
const updateAndDelete = async (userToRemove) => {
const session = await db.startSession()
try {
session.startTransaction();
const user = await User.findById(userToRemove, {session: session})
const {assignedBy} = user
await user.remove({session: session})
await Task.updateMany({asignTo: userToRemove}, {asignTo: assignedBy}, {session: session})
await session.commitTransaction();
} catch(e) {
await session.abortTransaction();
}
session.endSession();
}
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.如果一切正常,您提交事务并保存所有更改( if
需要,您也可以添加一些异常),否则您可以回滚并且不会丢失任何数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.