Why does my JavaScript file fail to retrieve the model.findByPk() method with the parameter "/:id"?

When attempting to retrieve items from the database based on their id, I am encountering an issue where Insomnia is returning an empty object. Specifically, in the code snippet below, my goal is to fetch a category by its ID while also retrieving any associated Products. Could you possibly point out what I might be overlooking here? Thank you for your help!

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);
  }
});

https://i.sstatic.net/8RFgB.png

https://i.sstatic.net/6LQRA.png

Answer №1

When utilizing the findByPk method, it is essential to provide the specific key you wish to retrieve. To achieve this in your code, follow these steps:

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);
  }
});

To do this, extract the id from the URL using req.params.id and pass it as a parameter to findByPk. It's advisable to validate that the id is an integer before proceeding with the operation :)

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

Mastering the art of scrolling and selecting items concurrently using the mouse in Vue

Struggling with a fascinating challenge of scrolling while selecting items using mouse drag in both up and down directions. Here's a screenshot for reference: https://i.stack.imgur.com/giMwY.png Check out my code: https://codesandbox.io/s/select-i ...

Ensuring radio button validation prior to redirecting to contact form

I created a survey form using HTML and CSS. I am looking to add validation to the questions before redirecting to the Contact form page. Currently, when a user clicks on the submit button in the Survey form, the page redirects to the contact form. Howeve ...

Is there a way to showcase individual components on a single surface one at a time?

Let me try to explain my issue as clearly as possible! I am currently working on a website using React and Material-UI. On one of my pages, I have a Paper component where I want to display different components that I have created, but only one at a time. ...

Guidelines on populating a Vue array with data fetched from an Axios request

The v-breadcrumbs component is used to display data from the breadcrumbs array, which works seamlessly with static data. <v-row> <!-- Breadcrumbs --> <v-col class="d-flex"> <v-breadcrumbs :items="breadcrumbs"></v ...

JavaScript - Issues with Cookie Setting

I created a function for setting cookies: function storeCookie(cname, cvalue, exdays){ var d = new Date(); d.setTime(d.getTime() + (1000*60*60*24*exdays)); var expires = "expires="+d.toGMTString(); document.cookie = cname + "=" + cvalue + ...

When is it appropriate to use app.use compared to when should app.all be used?

Within the documentation of express, there is an example that showcases the following: app.use('/user/:id', function (req, res, next) { console.log('Request Type:', req.method) next() }) This situation can be somewhat puzzling sin ...

Building a favorite feature in Django using HTML

Currently, I am working on implementing an Add to Favorite feature. So far, I have succeeded in displaying a button with an icon based on the value of the is_favorite field, but I am facing difficulties updating my database. I would like to know: How can ...

Timeout error of 10000ms occurred while using await with Promise.all in Mocha unit tests

Document: index.ts // Default Exported Classes getItemsA() { return Promise.resolve({ // Simulating API call. Mocking for now. success: true, result: [{ itemA: [] }] }); } getItemsB() { return Promise.resolve({ // Simulating API cal ...

What is preventing me from saving my session in Express.js (MERN Stack)?

I've been struggling to save a user's email in the session for my express.js project. No matter what I try, whenever I call another function, the session stays undefined. I've been working on this issue for weeks now and can't seem to c ...

Transitioning to TypeScript: Why won't my function get identified?

I am in the process of transitioning a functional JavaScript project to TypeScript. The project incorporates nightwatch.js Below is my primary test class: declare function require(path: string): any; import * as dotenv from "dotenv"; import signinPage = ...

Problem with resizing in CSS and jQuery

I need help creating a chatbox that can be resized. I've almost got it, but the bottom part of the chatbox detaches when I resize it. Also, I'm having trouble making the userList a fixed size that won't be affected by resizing. Check out th ...

There are no documents found by calling db.collection.find

Just getting started with my journey in learning Express, Node, and Mongojs! I decided to create a small MongoDB database called 'users' and when I run: db.users.find() in the Mongo shell, I receive an array of documents. In my Express app&ap ...

Next.js with Express Application Deployment to Elastic Beanstalk: Troubleshooting Error 502

I am encountering persistent 502 Bad Gateway errors while attempting to deploy a next.js application using express to Electric Beanstalk. 2020/03/02 15:26:28 [error] 8286#0: *172 connect() failed (111: Connection refused) while connecting to upstream, ...

Issue with function not being triggered upon using the .click event

I am attempting to trigger a function on a click event using $(this) in order to catch the event and execute a function. Despite trying different methods, I continue to encounter an error flagged in Firebug: SyntaxError: missing ) after argument list I ...

How can I dictate the placement of a nested Material UI select within a popper in the DOM?

Having trouble placing a select menu in a Popper. The issue is that the nested select menu wants to mount the popup as a sibling on the body rather than a child of the popper, causing the clickaway event to fire unexpectedly. Here's the code snippet f ...

Develop a feature within a standard plugin that allows users to add, remove, or refresh content easily

I have developed a simple plugin that builds tables: ; (function ($, window, document, undefined) { // Define the plugin name and default options var pluginName = "tableBuilder", defaults = { }; // Plugin constructor func ...

Choose all the checkboxes that use Knockout JS

Struggling with implementing a "select all" checkbox feature as a Junior developer on a complex project utilizing knockout.Js and Typescript. I can't seem to figure out how to select all existing checkboxes. Here is the HTML: <td> <inp ...

Preventing blank text entries in a task management application

Is there a way to determine if the text input provided by the user is empty or contains some text? I'm in the process of developing a TO-DO app and I'd like it so that if a user fails to enter anything into the text area and clicks on "add", the ...

Toggling dropdown menus with conditional Jquery statements

I am experiencing some discomfort. :) I've been working on a calorie calculator that includes a dropdown for various dietary preferences. Currently, when a user clicks the button, the dropdown appears and disappears when clicking outside the button. ...

To access an express server, use port 3000, while port 8081 is designated for react native. Learn how to send

I am currently developing an Avatar Builder app using React Native that I plan to deploy on both iOS and Android platforms. My server is running on Express, which uses localhost:3000, while React Native runs on localhost:8081. import axios from 'axio ...