Search code examples
typescriptmongodbmongoose

MongoDB Remove Many Documents with an array of objects where multiple fields must match


So I have a very particular question and have code written for it that works, I just don't like it, since there is an await in a for-loop which seems like bad practise, so is there a better way to do this?

const deleteDocuments = async (myObjects:Array<MyObject>) => {
  try {
    for (const myObject of myObjects) {
      await MySchema.findOneAndDelete(
        {
          $and: [
            { prop1: myObject.prop1 },
            { prop2: myObject.prop2 },
            { prop3: myObject.prop3 }],
        },
      );
    }
    const updatedDocuments = MySchema
      .find({}, { _id: 0 })
      .sort({ prop1: 1 });
    return updatedDocuments;
  } catch (e) {
    console.log(`Unexpected Error: ${(e as Error).message}`);
  }
};

This code seems to work, but I don't like it and I don't know how to write it properly.


Solution

  • ok, for those interested in the future, this is how I solved this (with a bit of help from chatGPT :p)

    try {
        const queryArray = myObjects.map((myObject) => ({
          $and: [
            { prop1: myObject.prop1 },
            { prop2: myObject.prop2 },
          ],
        }));
        const deletionData = await MySchema.deleteMany(
          { $or: queryArray },
          { new: true, _id: 0 },
        ).sort({ prop1: 1 });
        if (!deletionData) {
          console.log('Something went wrong while deleting objects');
          return ;
        }
        if (deletionData.deletedCount > 1) {
          console.log(`Deleted ${deletionData.deletedCount} objects`);
          return ;
        }
        console.log('Tried to delete objects, but none deleted');
        return ;
      } catch (e) {
        console.log(`Unexpected Error: ${(e as Error).message}`);
      }```