简体   繁体   中英

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.

{
  _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

{
  _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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM