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

Tips for ensuring a consistent highlight for an active link in Bootstrap

Does anyone have a solution for maintaining highlighted links on a web page? <div id="productnav"> <nav> <ul class="nav"> <li><a href="<?php echo $prefix; ?>pages/one.php?category=1" id="navelement1"<?php if ($c == 1) e ...

Despite having unique ids, two file input forms are displayed in the same div in the image preview

Running into a minor issue once again. It may not be the most eloquent query, but I'm genuinely stuck and in need of some assistance. I am attempting to showcase image previews of selected files in a file input form. I have a jQuery script that reads ...

Utilizing Ajax looping to generate dynamic HTML content with Bootstrap tabs

I am looking for a way to fetch multiple JSON files and display the data from each file in separate Bootstrap 3 Tabs. I understand that the getJSON function does not wait for completion before moving on, but I need help with using callbacks in situations ...

Guide on redirecting a Next.js app to HTTPS using cPanel

As a newcomer to Reactjs and Nextjs, I am working on an online shop project that I have deployed on a CPanel. Now, I'm looking for guidance on how to redirect it to the SSL port HTTPS. Can anyone help me with this? Here is a snippet of my app.js: con ...

Meteor, enhanced with the dynamic Iron Router module and integrated

I am working on a project using Meteor (Meteor.com) and I want to incorporate iron-router for the page routing along with the pre-existing accounts-ui package for login functionality. Previously, my {{loginButtons}} functioned properly, but ever since I i ...

Designing access to data in JavaScript

As I work on developing my single page app, I find myself diving into the data access layer for the client-side. In this process, a question arises regarding the optimal design approach. While I am aware that JavaScript is callback-centric, I can't he ...

Navigating with Vue Router in a Nuxt JS vuex Store

In my app, I'm currently developing a login/register system using Firebase and Vuex for authentication and database management. Within Nuxt JS, I have implemented actions to create a user, log them in, and sign them out. After a successful registrati ...

Dealing with HTML and Escaping Challenges in jQuery Functions

Here is a string I have: var items = "<div class='item'><div class='item-img' style='background-image: url('images.123.jpg')'></div></div>" I am looking to update the inner HTML of a div: $ ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. Here is the code snippet: const InputBox = () => { const [value, ...

Tips for sorting server components using a URL search parameter [Next.js, Prisma]

My goal is straightforward: I want to be able to filter my Prisma database based on parameters passed in the URL when I click on a CategoryBox. After clicking on a CategoryBox, my URL does change to something like http://localhost:3000/?category=XYZ, but ...

It is important to ensure that the user returned by the onAuthStateChanged function in

server admin.auth().createCustomToken(uuid) .then((customToken) => { admin.auth().createUser({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed989e889fad88958c809d8188c38e8280">[email protected] ...

An unspecified number of Ajax requests being made within a loop

Here is the dilemma I'm facing, despite trying different recommendations from StackOverflow: Situation: I am utilizing the Gitlab API to display all the "issues" in the bug tracker of a specific project on the system. Challenges: Everything wor ...

Troubleshooting deployment issues with aws-amplify and Next.js due to conflicts in aws-exports.js

As a newcomer to web development and the react/next/amplify ecosystem, I've been experimenting with it lately and finding it to be quite impressive. However, I'm facing challenges when it comes to deploying my app. It seems like there might be an ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

What is the default method for automatically disabling drop down fields?

I've created a script that will gray out a drop-down field if a prior selection wasn't made. Once the appropriate choice is selected, the grayed-out field will become active. My query is, how can I set the drop-down field to be initially grayed ...

Enhancing the Calculator Functionality in a React Program

I'm struggling to incorporate a reset button into the input field, similar to CE on a calculator. I'm facing challenges when it comes to integrating it within the existing code structure. import { useRef } from "react"; import './A ...

After my jQuery functions are executed, my CSS rules are loaded

Struggling with the communication between CSS and jQuery, I find myself torn. In CSS, my rules are often very specific, like this: div#container > div#contentLeft { //Code here } However, when I add jQuery to spice up my site, the CSS rules seem to ...

Error encountered with select2 when using a remote JSONP dataset

When attempting to query the Geonames data using select2, everything seems to work fine with formatting the results. However, an error occurs once the results are populated, which I suspect is preventing the formatSelection function from running properly. ...

Preventing clicks within an iframe

Within an iframe, I have HTML content that includes hyperlinks. I need to prevent clicks on these hyperlinks. I managed to accomplish this using jQuery as shown below. However, I prefer not to use jQuery for this task. How can I achieve the same result ...

What is the best way to obtain a reference to the parent form element within an AngularJS directive?

Here is the HTML code I am working with: <form name="my-form"> <div class="col-sm-4"> <input type="phone" name="mobileNumber" ng-model="form.mobileNumber" value="0439888999" required> </div> </form> In addition, I ha ...