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!