Is it possible to have various optional query parameters in Express?

In my Express application, I have a route that sends a GET request to the 'challenges' collection in MongoDB. This route is designed to find a specific challenge by its section number and challenge number.

Here is the code snippet for this functionality:

// @route           GET api/challenge?section=_&challenge=_
// @description     Get challenge by section number and challenge number
// @access          Private

router.get('/', auth, async (req, res) => {
  try {
    const challenge = await Challenge.find({
      section_no: req.query.section,
      challenge_no : req.query.challenge,
    });

    if (!challenge) {
      return res.status(400).json({ msg: 'Challenge not found' });
    }

    return res.json(challenge);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

This code works perfectly when tested on Postman. When providing both query parameters 'section' & 'challenge', it successfully retrieves the desired challenge data.

However, my question now is how can I enhance this code so that I can optionally query ONLY the section OR BOTH the section & challenge. For example, if I were to make a request like:

api/challenge?section=1

It should return all challenges in section 1.

But at the same time, I still want to be able to fetch a specific challenge by using the query:

api/challenge?section=1&challenge=1

This should return data on the first challenge in section 1.

Thank you in advance for any help provided!

Answer №1

To filter your data based on query strings, you can create a filter object in the following way:

router.get('/', auth, async (req, res) => {
  try {
    const filter = {};
    if (req.query.category) filter.category_name = req.query.category;
    if (req.query.type) filter.type_name = req.query.type;

    const result = await Data.find(filter);

    if (!result) {
      return res.status(404).json({ msg: 'Data not found' });
    }

    return res.json(result);
  } catch (error) {
    console.error(error.message);
    res.status(500).send('Internal Server Error');
  }
}); 

Answer №2

Another option is to utilize the spread operator, as the keys in question match those in the database query:

router.get('/', auth, async (req, res) => {
  try {
    const challenge = await Challenge.find({
      ...req.query,
    });

    if (!challenge) {
      return res.status(400).json({ msg: 'Challenge not found' });
    }

    return res.json(challenge);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

In this scenario, it's important to note that the query must contain either "challenge_no" and "section_no" keys or alternatively support "challenge" and "section" keys when accessing the query object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered during the creation of a new Angular application (npm ERROR! 404 Not Found: @angular/animations@~7.1.0.)

I am currently using Windows 10, Node v11.0.0, and Angular CLI: 7.1.4. I encountered an error when trying to create a new Angular application. The error message is npm ERR! code E404 npm ERR! 404 Not Found: @angular/animations@~7.1.0. Error stack: 0 info ...

The Express router completely bypasses a specific middleware

I've implemented an authentication route using PassportJS that looks like this: router.post('/', passport.authenticate('local', { failureRedirect: '/' }), async (req, res, next, done) => { // Custom Middleware 1 ...

Is it possible to convert a type to a JSON file programmatically?

Recently, I have been tasked with implementing configuration files for my system, one for each environment. However, when it came time to use the config, I realized that it was not typed in an easy way. To solve this issue, I created an index file that imp ...

What is the best way to indicate alternative dependencies in NPM?

When stating the requirements of a Debian package, you have the option to use syntax such as exim | mail-transport-agent to specify that your package requires either exim or mail-transport-agent, without any preference between the two. I am interested in ...

What is the best way to obtain logs from a NodeJs application that is being run in forever npm

Is there a way for me to view the logs of my nodejs server after using forever start server.js? I want to see what is being logged, check for any live errors, and more. I searched through their documentation but couldn't find anything helpful. I need ...

"An unanticipated stream issue occurred within the pipeline" by Node.js

My application consists of Node.js, Express, and various middleware such as connect-assets and express.static. Everything is currently running on my local machine (OSX, using Node 0.8) in development mode (hence the use of express.static). An important d ...

Error in node.js: 'arraystring' is not a defined variable

Currently, I am working on a project that involves demonstrating User Input Validation with JOI by validating Nested Objects and Arrays. However, an issue has arisen where the error message arraystring is not defined keeps popping up. How can I resolve th ...

Discover the solution for seamless integration of TypeScript with the novel `exports` and `main` field

I am currently utilizing Node.js version 16.10.0 along with TypeScript 4.5.5. As part of my development process, I am in the midst of publishing a library and have implemented the following configuration: "main": "./dist/index.js", ...

The loading of npm installed Firebase in Angular4 is not successful

I am currently facing an issue while trying to integrate npm installed Firebase with my Angular4 application. I have successfully installed the latest version of Firebase (version 4.1.1) using npm and verified that the installation was successful. Below is ...

Having trouble receiving the desired JSON format with xml2js, is there a way to resolve this issue?

After attempting to convert an XML file obtained from an external server into JSON using xml2json, it appears that the conversion is not producing a valid JSON output. It seems like there may be an issue with missing quotes for the keys. Are there adjustme ...

Discovering the number of individuals assigned to a specific role with discord.js

I am interested in determining the number of members with a specific role in my server. My approach involves using the following code snippet: const bots = guild.roles.cache.find(role => role.name == "Bots"); console.log(bots.members.cache.siz ...

The Loopback access control list (ACL) for the admin role is failing to be

Seeking assistance with troubleshooting why my 'admin' role is not functioning in loopback 3.x. Here are the codes I am using: script.js - Contains code for creating admin roles in a postgres database. module.exports = function (app) { var User ...

Using Express and React with Socket.io

I am currently working on setting up a basic WebSocket connection using Socket.io, Express, and ReactJS. Below is the code for the server: const express = require('express'); const socket = require('socket.io'); const path = require(& ...

In search of a fresh and modern Facebook node template

I've been on the hunt across the internet for a quality node.js Facebook template, but all I seem to stumble upon is this https://github.com/heroku/facebook-template-nodejs. It's okay, but it's built using express 2.4.6 and node 0.6.x. I wan ...

Custom error handling in Passport.js for unauthorized requests and bad requests

Utilized passport-jwt and attempting to generate a custom error response when the user is invalid (empty email|password) or not registered. api.js const passport = require('passport'); const router = require('express-promise-router' ...

Solve the mystery of hidden IP addresses in Node.js with the help of the DNS module

Is it possible to achieve the same result as running the command dns-sd -q a5b3ef18-2e66-4e24-91d2-893b93bbc1c1.local on Mac OSX using Node.js? It appears that the dns module in Node.js is primarily used for converting website addresses to IP addresses, no ...

Ideas for effectively reusing MongoDB Mongoose queries in Node.js

Can you re-use an existing exec mongodb/mongoose query in nodejs? For example, let's say I create a query like this to check if a user exists: const inviter = await User.findOne({ _id: req.userData._id }).exec() // There is more code below before upd ...

What is the best way to set jade as a global variable in a node.js Express application?

Currently, the routing function shown below is operational: exports.summary = function(req, res, next) { var jade = require('jade'); res.render('myView', { main: jade.renderFile('./views/summary.jade') }); }; The ...

The res.download method in a node.js express app does not display the correct filename upon downloading

Starting with what I have: core.app.get('/download/:key', function (req, res) { require("./../../module/fileupload.js").download(req.params.key, function(file, filename) { console.log(file + " - " + filename); if (file != nul ...

Leveraging NodeJS functions within an HTML environment

After successfully creating a NodeJS back-end, I encountered a challenge. How can I connect my back-end to my front-end HTML/CSS page and utilize my NodeJS functions as scripts? ...