Access model information from a controller with the help of Next.js and Sequelize

I'm currently working on a project involving Vue.js as my frontend and Next.js as my backend. While everything seems to be running smoothly, I am facing an issue with retrieving my model data back to my controller...

Additional details:

  • I have utilized Sequelize for creating my models, migrations, and seeders.
  • The database is PostgreSQL

Below is my controller (recetteController.js) where I invoke the findAllRecette() method :

// import { Recette } from '../../models/recette'; 
const { Recette } = require('../../models/recette'); 
// const Recette = require('../../models/recette');

console.log(Recette);

export default async function handler(req, res) {
    try {
        const recettes = await Recette.getAllRecette(); 
        res.status(200).json(recettes);
    } catch (error) {
        res.status(500).json({ error: 'An error occurred while fetching the recipes' });
    }
}

Here is my model (recette) where the getAllRecette() function is defined :

'use strict';
const { Model } = require('sequelize');

module.exports = (sequelize, DataTypes) => {
  class Recette extends Model {
    static associate(models) {
      Recette.belongsTo(models.Difficulte, { foreignKey: 'id_difficulte', as: 'difficulty' });
      Recette.belongsTo(models.Categorie, { foreignKey: 'id_categorie', as: 'category' });
    }
  
    // Fetch all recipes
    static async getAllRecette() {
      console.log("SUCCESS");
      const recettes = await this.findAll();
      return recettes;
    }
  }

  Recette.init({
    name: DataTypes.STRING,
    description: DataTypes.STRING,
    serving: DataTypes.INTEGER,
    time: DataTypes.INTEGER,
    id_difficulty: DataTypes.INTEGER,
    id_category: DataTypes.INTEGER,
    image: DataTypes.TEXT
  }, {
    sequelize,
    modelName: 'Recipe',
  });

  return Recipe;
};

I do not have prior experience in this setup apart from Laravel, so there might be mistakes in my approach...(MVC)

The issue arises when the console.log(Recette) output is either 'undefined' or '[Function (anonymous)]' depending on how I import the Recette object

I also attempted calling findAll() directly within my controller but it did not resolve the problem of the controller failing to locate my model.

Please, I have spent considerable time trying to resolve this! Thank you!

Answer №1

If you want to establish a database connection in your Node.js application, consider using the import {} syntax instead of require() and create a separate JavaScript file for connecting to the database. Here's an example:

//database.js
import { Sequelize } from 'sequelize';

const sequelize = new Sequelize('db_name', 'user', 'password', {
  host: 'host_name',
  dialect: 'dialect', //e.g. postgres
  logging: console.log, 
});

(async () => {
  try {
    await sequelize.authenticate();
    console.log('Database connection successfully established.');
  } catch (error) {
    console.error('Error connecting to the database:', error);
  }
})();

export default sequelize;

You can then use this database connection file in your model files like this: import sequelize from 'database';

//model.js
import { DataTypes, Model } from 'sequelize';
import sequelize from 'database';

class MyClass extends Model {
  static associate(models) {
   
  }

}

export default (sequelize) => {
  Recette.init({
    name: DataTypes.STRING,
    description: DataTypes.STRING,
    //... 
  }, {
    sequelize,
    modelName: 'MyClass',
  });

  return MyClass;
};

export { MyClass }; 

Finally, for the controller part, you can structure it as follows:

import {MyClass} from '../models/myClass';

export default async function handler(req, res) {
  try {
    const datas = await MyClass.findAll(); 
    res.status(200).json(datas);
  } catch (error) {
    res.status(500).json({ error: 'Error while fetching datas' });
  }
};

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

Challenges with the efficiency of the Material UI Datagrid

I am currently using MUI Datagrid to display my records, but I am experiencing delays with my modal and drawer components. Even after attempting to optimize with useMemo for my columns, I have not been able to achieve satisfactory performance. https://i.st ...

watchWebpack is compiling all the files

As per the webpack documentation on watching files webpack can keep an eye on files and recompile them whenever there are changes. My understanding is that this implies webpack will only compile the files that have been modified. I have a configuratio ...

Design your own arrow Slideshow + Next.js + Sass styling

In my current project, I am utilizing the swiper slider within a Next.JS development environment and styling with Sass. However, despite following the documentation guidelines to apply custom styles to the slider arrows, they do not display correctly. My ...

Trigger Object RuntimeError

Initially, I attempted to pass the object :id to the URL and it was successful. However, when I tried to pass the object to the list, I encountered a ReferenceError. index.ejs: <tr> <th class="text-center">AWB NO</th> <th c ...

Encountering the error "Cannot access property 'stroke' of undefined" when utilizing constructors in React and p5

Hi there, I'm having trouble with my React code and could really use some assistance. Being new to React, I'm trying to create a collision system between multiple bubbles in an array, but I keep running into this undefined error: import React, ...

Rotation snapping feature 'control.setRotationSnap' in TransformControls.js (Three.js) is not functioning properly

Attempting to utilize the functionality of "control.setRotationSnap" from the script "TransformControls.js", but unfortunately, it is not working as expected. After conducting some research, I came across a forum post suggesting that the code might not be ...

Issue with TypeORM Many-to-Many relation returning incorrect data when using the "where" clause

I'm facing an issue with my database tables - User and Race. The relationship between them is set as Many to Many , where a Race can have multiple Users associated with it. My goal is to retrieve all the Races that a particular user is a member of. Ho ...

Using JavaScript with namespaces in C#

I am currently trying to explore AJAX and web services through self-teaching using C# and JavaScript. After doing some research on Google, it seems like I might be facing a namespace problem. Here is the snippet of my code: using System; using System.Col ...

Is it possible to directly add a child in HTML from nodejs?

I'm in the process of developing a chat application that requires users to select a room from a list of available rooms stored in <datalist> options, which are fetched from a SQL table on the server. Within my login.html file, users are prompte ...

"Unlocking the Secrets of Extracting Data from Highlighted Cells in Excel with Node.js

I created a script in node.js to extract information from an excel file. Each row contains a highlighted cell (only one). Right now, I am utilizing the xlsx package to access the data. Here is my code snippet for retrieving data from the sheet: var XLSX = ...

I am sending an AJAX request to a remote server in order to retrieve access records

Currently, I am attempting to retrieve data by sending an ajax request to a remote server controller from my current remote page. Below is the code for my first remote view page: <?php include 'header.php'; ?> <script src="/assets/js/ ...

Developing a JavaScript library that utilizes flow type annotations and provides access to various data types

I am currently developing a library intended for use by third parties. I have opted to utilize flowtype as the typing system for specific reasons within my organization. This library presents React components with annotations. The library itself is annota ...

Distributing JWT to the recipient using Express

Allow me to provide you with an overview of my application, which is quite straightforward. The main concept revolves around a user inputting their accountname and password into an html form on the /Login page like so: <form action="/Login" m ...

Tips for clearing all content within a React Material UI table

How can I create a reset button to clear a table filled with user input data, without having to write functions from scratch? For example, similar to using clearLayer() for clearing a leaflet map. Thank you for any suggestions! //example of dynamical ...

Reduce the file size of CSS and JS files for Magento

We are facing an issue with minifying CSS and Javascript for our Magento website. Currently, the size of our website is 1.1 MB and we aim to reduce it to 1 MB or even lower if possible. I tried using the "CSS Settings" and "Javascript Settings" functions ...

Display function not functioning properly following AJAX request

I'm working on a functionality where I want to initially hide a table when the page loads, and then display it with the results when a form is submitted using Ajax. The issue I'm facing is that the code refreshes the page and sets the table back ...

Sending numerous array values from datatables

I am currently working with datatables that allow for multiple selections. When I select 3 rows from top to bottom (as shown in this picture), the console.log returns this specific value for each row selected. The value that needs to be passed to the next ...

file_put_contents - store user-defined variables

When I execute this script, it successfully generates the html page as expected. However, I am encountering challenges in incorporating variables, such as the $_GET request. The content is enclosed in speech marks and sent to a new webpage on my site usin ...

Combining intersecting sets within an array of sets

I am working with an array that contains minimum and maximum values for various sets. Here is an example of what the array looks like: Array ( [0] => Array ( [0] => 1200 [1] => 2400 ) [1] => Arr ...

Automatically reduce the size of Java Script files and CSS files with compression

I'm currently working with Google App Engine and JQuery. I'm looking for a solution that can automatically compress my JavaScript and CSS files when deploying them to the GAE server. It's quite cumbersome to manually compress all the files e ...