add unit suggestion based on ingredient

This commit is contained in:
2025-08-10 14:04:14 +01:00
parent 089d33925b
commit fbb6ce0441
4 changed files with 470 additions and 4 deletions

View File

@@ -65,6 +65,52 @@ router.get('/ingredients/suggestions', async (req, res) => {
}
});
// Get unit suggestions for a specific ingredient
router.get('/ingredients/units', async (req, res) => {
try {
const { ingredient } = req.query;
if (!ingredient) {
return res.json([]);
}
// Find units used with this specific ingredient
const unitSuggestions = await Recipe.aggregate([
{ $unwind: '$ingredients' },
{
$match: {
'ingredients.name': {
$regex: ingredient,
$options: 'i'
}
}
},
{
$group: {
_id: { $toLower: '$ingredients.unit' },
unit: { $first: '$ingredients.unit' },
count: { $sum: 1 },
avgAmount: { $avg: '$ingredients.amount' }
}
},
{ $sort: { count: -1, unit: 1 } },
{ $limit: 8 },
{
$project: {
_id: 0,
unit: 1,
count: 1,
avgAmount: { $round: ['$avgAmount', 2] }
}
}
]);
res.json(unitSuggestions);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Get all recipes
router.get('/', async (req, res) => {
try {