diff --git a/package.json b/package.json index 5a19603..fd33fe5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@togethercrew.dev/db", - "version": "3.0.28", + "version": "3.0.29", "description": "All interactions with DB", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/models/schemas/Platform.schema.ts b/src/models/schemas/Platform.schema.ts index c153d95..1d73e99 100644 --- a/src/models/schemas/Platform.schema.ts +++ b/src/models/schemas/Platform.schema.ts @@ -34,10 +34,43 @@ const platformSchema = new Schema( platformSchema.plugin(toJSON); platformSchema.plugin(paginate); +const announcementDeletion = async (platformId: any): Promise => { + // ?in case the platformID (inputted platformID) of each item in the data array field matches, delete that announcement. + const announcementsWithAllDataOnSamePlatformIds = await Announcement.aggregate([ + { + $match: { + 'data.platform': platformId, + }, + }, + { + $project: { + allMatch: { + $not: [ + { + $elemMatch: { + 'data.platform': { $ne: platformId }, + }, + }, + ], + }, + }, + }, + { + $match: { + allMatch: true, + }, + }, + ]); + const idsToDelete = announcementsWithAllDataOnSamePlatformIds.map((announcement) => announcement._id); + await Announcement.deleteMany({ _id: { $in: idsToDelete } }); + + await Announcement.updateMany({ 'data.platform': platformId }, { $pull: { data: { platform: platformId } } }); +}; + platformSchema.pre('remove', async function (this: Document) { const platformId = this._id; await Community.updateOne({ platforms: platformId }, { $pull: { platforms: platformId } }); - await Announcement.updateMany({ 'data.platform': platformId }, { $pull: { data: { platform: platformId } } }); + await announcementDeletion(platformId); }); export default platformSchema;