Home > Back-end >  How update and delete bulk operation in mongodb?
How update and delete bulk operation in mongodb?

Time:01-09

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
}

CodePudding user response:

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.

  • Related