Hi, I apologise for quality of post I am new here.
I have a coding issue. I have this endpoint
router.get('/by-category', authMiddleware, async (req, res) => {
try {
// Pagination setup
const limit = parseInt(req.query.limit) || 5;
const page = parseInt(req.query.page) || 1;
const skip = (page - 1) * limit;
// Extract search query and category parameters
const searchQuery = req.query.searchQuery || ''; // If no search query, it's an empty string
const categoriesParam = req.query.categories; // Categories query param, e.g. "Back,Arms"
const includeUncategorized = req.query.includeUncategorized === 'true';
// Debugging log: check the search query
console.log('Received search query:', searchQuery);
// Split categories into an array and capitalize the first letter of each category
const categories = categoriesParam
? categoriesParam.split(',').map(c => c.trim().replace(/^\w/, (c) => c.toUpperCase()))
: null;
// Initialize exercises query object
let exercisesQuery = { image_url: { $exists: true, $ne: '' } }; // Only exercises with an image
// Apply category filter if categories are provided
if (categories && categories.length > 0) {
exercisesQuery.category = { $in: categories }; // Only include exercises in selected categories
} else if (!includeUncategorized) {
exercisesQuery.category = { $ne: 'Uncategorized' }; // Exclude 'Uncategorized' if not requested
}
// Apply search query filter if provided (search by exercise title/name)\
if (searchQuery) {
// Escape special characters in the search query
const escapedSearchQuery = searchQuery.replace(/[.*+?^=!:${}()|\[\]\/\\]/g, "\\$&"); // Escape regex special chars
exercisesQuery.name = new RegExp(escapedSearchQuery, 'i'); // Case-insensitive search on 'name'
console.log('MongoDB query:', exercisesQuery); // Log the query to check for correctness
}
// Fetch exercises from the database with pagination and filters applied
const exercises = await Exercise.find(exercisesQuery)
.skip(skip)
.limit(limit);
// Group exercises by category (case-insensitive)
const grouped = exercises.reduce((acc, exercise) => {
const category = (exercise.category || 'Uncategorized').toLowerCase();
if (!acc[category]) {
acc[category] = [];
}
acc[category].push(exercise);
return acc;
}, {});
// Log the grouped result and search query to check correctness
console.log('Grouped exercises:', grouped);
console.log('Search query used:', searchQuery);
// Return the grouped exercises
res.json(grouped);
} catch (err) {
console.error('Error grouping exercises by category:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
and model
const mongoose = require('mongoose');
const { v4: uuidv4 } = require('uuid');
const ExerciseSchema = new mongoose.Schema({
exerciseId: { type: String, default: uuidv4, unique: true }, // Add a UUID for consistency
name: { type: String, required: true },
slug: String,
description: String,
instructions: [String],
primary_muscles: [String],
secondary_muscles: [String],
equipment: [String],
category: String,
image_url: String, // Store the image URL directly
realistic_image_url: String,
});
module.exports = mongoose.model('Exercise', ExerciseSchema);
The issue is the regex for searching isnt working. I try to build the query based on if a seearchquery string is provided but get no result when I call the api, even though when I try the same query directly in the dashboard, I get results. I also tried
if (searchQuery) {
exercisesQuery.name = { "$regex": searchQuery, "$options": 'i' }; // Case-insensitive search on 'name'
console.log('MongoDB query:', exercisesQuery); // Log the query
}
but same issue. I’m I missing something here? What could be some potential issues for this?
Thank you for reading.