Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
JS file not pulling model.findByPk() using "/:id"?

I'm trying to pull items from my database using each item's id, but am receiving an empty object when running it through Insomnia. For example, in the code below, I would like to pull a category by ID, but also include any associated Products. Any idea what I might be doing wrong? Thank you in advance!

router.get('/:id', async (req, res) => {
  try {
    const oneCategory = await Category.findByPk({
      include: [{ model: Product }]
    });
    // console.log(oneCategory);
    if (!oneCategory) {
      res.status(404).json({ message: 'No category found with that id!' });
      return;
    }
    res.status(200).json(oneCategory);
  } catch (error) {
    res.status(500).json(error);
  }
});

Empty Object in Insomnia

Category Table in DB

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

When calling the findByPk method, you need to pass the key you are looking for. In this particular case, the code should look like this:

router.get('/:id', async (req, res) => {
  try {
    const oneCategory = await Category.findByPk(req.params.id, {
      include: [{ model: Product }]
    });

    if (!oneCategory) {
      res.status(404).json({ message: 'No category found with that id!' });
      return;
    }
    res.status(200).json(oneCategory);
  } catch (error) {
    res.status(500).json(error);
  }
});

So just grab the id from the URL with req.params.id and pass it to findByPk. However, it could be a good idea to check so that the id is in fact an integer before doing so :)

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!