add ingredient suggestions during recipe creation
This commit is contained in:
@@ -21,6 +21,50 @@ function authenticateToken(req, res, next) {
|
||||
});
|
||||
}
|
||||
|
||||
// Get ingredient suggestions for autocomplete
|
||||
router.get('/ingredients/suggestions', async (req, res) => {
|
||||
try {
|
||||
const { q } = req.query; // Search query
|
||||
|
||||
if (!q || q.length < 2) {
|
||||
return res.json([]);
|
||||
}
|
||||
|
||||
// Aggregate unique ingredient names from all recipes
|
||||
const suggestions = await Recipe.aggregate([
|
||||
{ $unwind: '$ingredients' },
|
||||
{
|
||||
$match: {
|
||||
'ingredients.name': {
|
||||
$regex: q,
|
||||
$options: 'i'
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: { $toLower: '$ingredients.name' },
|
||||
name: { $first: '$ingredients.name' },
|
||||
count: { $sum: 1 }
|
||||
}
|
||||
},
|
||||
{ $sort: { count: -1, name: 1 } },
|
||||
{ $limit: 10 },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
name: 1,
|
||||
count: 1
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
res.json(suggestions);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Get all recipes
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user