fix: ensure recipe deletion removes database entries, images, and favorites
All checks were successful
CI / update (push) Successful in 1m12s

Fixes critical bug where recipes could not be deleted properly. The delete function had an early return statement that prevented database deletion from executing, leaving orphaned entries. Additionally, deleted recipes were not removed from users' favorites lists.

Changes:
- Remove premature return statement blocking database deletion
- Fix malformed fetch call structure (headers were inside body JSON)
- Add UserFavorites cleanup to remove deleted recipes from all users' favorites
- Ensure complete cleanup: database entry, image files (hashed and unhashed), and favorites references
This commit is contained in:
2026-01-03 16:10:38 +01:00
parent 1addc4b1d7
commit cdcb5ee228
2 changed files with 20 additions and 5 deletions

View File

@@ -209,16 +209,15 @@
//alert(item.message)
return
}
return
const res = await fetch('/api/rezepte/delete', {
method: 'POST',
body: JSON.stringify({
old_short_name,
}),
headers: {
'content-type': 'application/json',
}
})
credentials: 'include',
}
})
if(res.ok){
const url = location.href.split('/')

View File

@@ -1,5 +1,6 @@
import type { RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../models/Recipe';
import { UserFavorites } from '../../../../models/UserFavorites';
import { dbConnect } from '../../../../utils/db';
import type {RecipeModelType} from '../../../../types/types';
import { error } from '@sveltejs/kit';
@@ -13,8 +14,23 @@ export const POST: RequestHandler = async ({request, locals}) => {
const short_name = message.old_short_name
await dbConnect();
// Find the recipe to get its ObjectId before deleting
const recipe = await Recipe.findOne({short_name: short_name});
if (!recipe) {
throw error(404, "Recipe not found");
}
// Remove this recipe from all users' favorites
await UserFavorites.updateMany(
{ favorites: recipe._id },
{ $pull: { favorites: recipe._id } }
);
// Delete the recipe
await Recipe.findOneAndDelete({short_name: short_name});
return new Response(JSON.stringify({msg: "Deleted recipe successfully"}),{
status: 200,
status: 200,
});
}