Filtering query String MongoDB

15 Views Asked by At

I am trying to filter my dataBS from MongoDB for that I have created the following route

route.get("/", getFilterRecipe);

with the following function

export async function getFilterRecipe (req, res) { try {

const { type, mealtime, preparationtime, difficulty, opinion } = req.query;

const filter = {};
if (type) filter.type = type;
if (mealtime) filter.mealtime = mealtime;
if (preparationtime) filter.preparationtime = preparationtime;
if (difficulty) filter.difficulty = difficulty;
if (opinion) filter.opinion = opinion;

const recipes = await Recipe.find(filter);


res.json(recipes);

} catch (err) {

console.error('Error:', err);
res.status(400).json({ error: err.message });

} };

nontheless when I try to filter the url for instance https://l4rnrz4l-4000.asse.devtunnels.ms/api/recipe?type=american&mealtime=lunch. I get back all the recipes rather than the filter ones.

Obviously I am doing something wrong but what is it?

Thanks for your time and help.

I have tried to parse the res.query and it doesn't work. To be honest dont really know what to do. Chat GPT is not helping me out either.

0

There are 0 best solutions below