0

Good morning everyone,

I'm stuck in this problem and I can't find a way to solve. I think is really easy to but I can't find the error. I'm just trying to create 3 routes with express to get all active tournaments, just one selected with the parameter and the latest 3 for the home page. For that, I have created three gets to fetch the data with different functions in my controller. But if I try to fetch the data with postman of the route "/activetournament" I receive this error. The only way to remove it is comment the other 2 gets. Thank you for your answers.

(node:17203) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "activetournaments" at path "_id" for model "Tournament"
const tournamentsCtrl = {};

const Tournaments = require("../models/Tournaments");

tournamentsCtrl.createTournament = async (req, res) => {
    console.log(req.body);

    const newTournament = new Tournaments(req.body);
    await newTournament.save();
    res.json({ message: "Tournament Saved" });
}


tournamentsCtrl.getTournament = async (req, res) => {
    const tournament = await Tournaments.findById(req.params.id);
    res.json(tournament);
}

tournamentsCtrl.homeTournament = async (req, res) => {
    const tournament = await Tournaments.find().sort({ _id: 1 }).limit(3);
    res.json(tournament);
}

tournamentsCtrl.actTournament = async (req, res) => {
    const tournament = await Tournaments.find({ "signup_dates.signup_end_date": { $gt: new Date() } });
    res.json(tournament);
}

module.exports = tournamentsCtrl;
const router = require("express").Router(); // Enrutador
const tournamentsCtrl = require('../controllers/tournaments.controller');
const auth = require('../middleware/auth');

//Create tournaments
//api/tournaments
router.post('/', tournamentsCtrl.createTournament);
router.get('/activetournaments', tournamentsCtrl.actTournament);
router.get('/:id', tournamentsCtrl.getTournament);
router.get('/', tournamentsCtrl.homeTournament);

module.exports = router;

1 Answers1

2

After observing your controller and routes code, I found where problem lies.

router.get('/activetournaments', tournamentsCtrl.actTournament);
router.get('/:id', tournamentsCtrl.getTournament);

For express.js, above two routes works as same, where in second route, in place of :id, it considers activetournaments, and proceeds further. So, when you hit API /activetournaments, it calls two routes

  1. router.get('/activetournaments', tournamentsCtrl.actTournament);
  2. router.get('/:id', tournamentsCtrl.getTournament);
    And your getTournament method accepts id and that id comes from req.params, which is in this case activetournaments.
    Solution for this problem is, use different convention to create routes such as,
router.get('/activetournaments', tournamentsCtrl.actTournament);
router.get('/tournamentById', tournamentsCtrl.getTournament);
Vikas Keskar
  • 1,158
  • 9
  • 17