'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();


Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Syed