Mohammad Yaser Ahmadi
Mohammad Yaser Ahmadi

Reputation: 5051

how to use deleteMany in transaction of mongoose

I want to delete an array of model schema from collection.

for removing one model I use

    let place = await Place.findById(placeId);

    const sess = await mongoose.startSession();
    sess.startTransaction();
    await place.remove({ session: sess });// remove place
    await sess.commitTransaction();

if place is a array

    let place = await Place.find({title : "Eiffel"}); // Array of Model

    const sess = await mongoose.startSession();
    sess.startTransaction();
    await place.deleteMany({ session: sess });// error ????
    await sess.commitTransaction();

Upvotes: 0

Views: 2830

Answers (2)

Syed
Syed

Reputation: 1

You could always map the array to create an array of unique id's of them documents, then delete it at such:

const idsToDelete = place.map((obj) => obj._id);
await Place.deleteMany({ _id: {$in: [...idsToDelete]} }).session(session);

The above utilises the $in operator, to only delete documents where the _id is any of those passed in to {$in: []}. This allows a quick work around to ensure the delete operation is using a transactional session.

Check this out for more info on the $in operator: https://kb.objectrocket.com/mongo-db/the-mongoose-in-operator-1015

Upvotes: 0

R2D2
R2D2

Reputation: 10737

await place.deleteMany({'xyz': 999}).session(sess);

Upvotes: 2

Related Questions