Searching for parameters wrongly triggering the id on a different route

Having recently delved into mongoose, I must apologize in advance for any misuse of terminology on my part.

Below is the content of my routes file:

const express = require('express');
const router = express.Router();
const passport = require('passport');
const controller = require('./clubController');
const authGuard = passport.authenticate('jwt', { session: false });
const verifyUser = require('./clubController').verifyUser;
const isSiteAdmin = require('./clubController').isSiteAdmin;

router.param('id', controller.params);

router.route('/')
    .post(authGuard, controller.newClub)
    .get(controller.allPublicClubs);

router.route('/:id')
    .put(authGuard, verifyUser(), controller.editClub)
    .get(controller.getClub);

router.route('/private')
    .get(controller.allPrivateClubs);

module.exports = router;

controller.params

exports.params = function(req, res, next, id) {
    Club.findById(id)
        .populate('creator teams', '-password -email -role')
        .exec()
        .then(function(club) {
            if (!club) {
                return res.status(404).send({ msg: 'No Club exists with that ID' });
            } else {
                req.club = club;
                next();
            }
        }, function(err) {
            // error handling
            next(err);
        });
};

controller.params activates when I send a GET request to /private. In theory, the params middleware I've set up should only activate when a called route uses an id parameter.

The value for the id argument in controller.params is being set as private, which corresponds to the route.

The error message I'm getting is as follows:

CastError: Cast to ObjectId failed for value "private" at path "_id" for model "club"

This was all functioning correctly yesterday; I have no clue what could have changed to cause it to stop working now.

Answer №1

The problem was resolved by rearranging the routes like this:

router.route('/:id')
    .get(controller.getClub)
    .put(authGuard, verifyUser(), controller.editClub);

I found it odd because the order was the same as before when it was working perfectly fine

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

The magnifying glass icon is missing from the autocomplete search feature

After creating an autocomplete search functionality that queries my mysql database, I encountered a slight issue. Here is the code snippet showcasing my implementation: <div class="search-bar"> <div class="ui-widget"> <input id="ski ...

Strategies for managing events within functional React components without relying on mutative operations

Based on insights from Cam Jackson, the recommendation is to utilize Redux and create small, stateless functional components. For example: const ListView = ({items}) => ( <ul> {items.map(item => <ItemView item={item}/>)} ...

Despite being deployed on Vercel, the process.env variables in Nextjs are still not functioning as expected

I'm currently working on a project that involves using 4 api keys that I need to keep hidden: STORYBLOK_API_KEY= EMAILJS_SERVICE_ID= EMAILJS_USER_ID= EMAILJS_TEMPLATE_ID= All of these keys are being accessed using process.env.XXX. What's inte ...

There seems to be a problem with how the navbar is being displayed in ResponsiveSlides.js

I am currently using WordPress, but I have come here seeking help with a jQuery/CSS issue. I am utilizing responsiveSlides.js to create a simple slideshow, however, when viewing it here at gallery link, it appears that something is not quite right. STEPS: ...

The Ultimate Slider: Highlighting Custom Navigation Link as Active While Navigating with Arrows

I have implemented custom navigation links for my slick slider in order to navigate to specific slides. The functionality works perfectly, but I encountered an issue when I added the built-in arrows provided by the slider. Whenever I use these arrows to n ...

Using Vue.js, you can set a method to return data directly to

Having just begun my journey with Vue, I find myself in a bit of a predicament. As part of my learning process, I am developing an app for tracking episodes in TV series. The initial step involves searching for series and adding them to a database. When co ...

Unable to establish a session on the Node server

I'm currently in the process of setting up a node server that includes login, logout, and authentication functionalities. However, I've encountered an issue with my code where after debugging, some debug information logs are being generated that ...

leafletjs: render Points of Interest (POIs) using canvas technology

I am looking for a way to efficiently draw multiple geo points using Leaflet and HTML5 canvas. My data source is geoJSON, but according to the documentation of Leaflet, drawing geo positions as canvas is currently not supported. var anotherGeojsonLayer = ...

Incorporating a helper JavaScript file to seamlessly integrate Typeform into a project built with Vue

Struggling with incorporating a typeform into my website through the use of both vue and laravel. The problem arises when trying to embed the typeform using a script, as Vue throws an error when attempting to include the script directly within the compone ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

URL Construction with RxJS

How can I efficiently create a urlStream using RxJS that incorporates multiple parameters? var searchStream = new Rx.ReplaySubject(1); var pageStream = new Rx.ReplaySubject(1); var urlStream = new Rx.Observable.create((observer) => { //Looking to ge ...

Issues with running grunt serve

I'm encountering issues with running my project in WebStorm IDE. When I enter grunt serve, I am faced with the following errors: grunt serve Loading "connect.js" tasks...ERROR >> SyntaxError: C:\Users\TT\Documents\ES\fr ...

Starting PM2 with multiple instances can be achieved by following these steps

While running my nodejs code with PM2, I encountered a requirement for multiple instances of nodejs executing the same code. To address this need, I created a script named "myscript.sh": cd ~/myproject PM2_HOME='.pm2_1' /usr/local/bin/node /u ...

What is the best way to merge multiple statements into one before passing them into a JavaScript method?

I am faced with several javascript statements like the ones listed below: $('#' + xxx_slot_name1).children().remove(); $('#' + xxx_ad_slot_name2).children().remove(); $('#' + xxx_ad_slot_name3).children().remove(); $('#& ...

PHP: Dynamically update div content upon submission

I am attempting to update the "refresh" div after clicking the Submit button and also at regular intervals of 5 seconds. Despite looking through various resources, I have not been able to find a solution that meets my requirements. <script src="h ...

Sharing data across multiple paths

route.post('/register',function(req,res){ //completed registration process // token value assigned as 'abc' }) route.post('/verify',function(req,res){ // How can I retrieve the token ('abc') here? }) I' ...

Encountering an issue when trying to execute the Yeoman generator

I was in the middle of following a tutorial on mean.js, which can be found at . However, when I ran the command yo meanjs, I encountered the following error: Error: Error: Command failed: C:\Windows\system32\cmd.exe /s /c "git --version" ...

Unable to perform surveillance on the htpp.get method

Example snippet: if (!this.scope.popupHtmlTemplate) { this.$http.get("widgets/pinpointcomponent/browseLibraries/resources/browseLibrariesDialogModal.html") .success((data: any) => { console.log("Processing success"+data) if (dat ...

The most effective method for dynamically incorporating tables into a Node.js and Express application using Sequelize

After conducting some research, I have hit a roadblock in finding the right solution. My project involves creating a personal budgeting application using node, Express, and Sequelize. The goal is to allow users maximum flexibility by dynamically generating ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...