Home > Mobile >  Error: No Sequelize instance passed in Nodejs
Error: No Sequelize instance passed in Nodejs

Time:11-24

I'm having this problem when I try to start my application or run some route. I can't understand why. Can anyone help?

The full error:

Error: No Sequelize instance passed
    at Function.init (D:\repo\lbr\node_modules\sequelize\dist\lib\model.js:1:13622)
    at initUser (D:\repo\lbr\db\models\USERS\user.js:20:7)
    at Object.<anonymous> (D:\repo\lbr\db\lbDB.js:33:8)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:\repo\lbr\controllers\UserController.js:1:16)

My app.js in the root of the directory, where the routes are configured:

const express = require("express");
const cors = require("cors");
const cookieParser = require("cookie-parser");

const app = express();

const users = require("./routes/users");

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors({ origin: "*", optionsSuccessStatus: 200 }));

app.use("/users", users);

module.exports = app;

/routes/users.js

const express = require("express");

const { listUsers, addUsers, deleteUsers, updateUsers } = require("../controllers/UserController");

const router = express.Router();

router.get("/users", listUsers);
router.post("/users", addUsers);
router.put("/users/:id", updateUsers);
router.delete("/users/:id", deleteUsers);

module.exports = router;

user controller:

const models = require("../db/lbDB");

/**
 * @param {import("express").Request} req
 * @param {import("express").Response} res
 */
async function listUsers (req, res) {
    try {
        res.status(200).send("Users.");
    } catch (err) {
        console.log(err);
        res.status(500).json({ message: err.message, err });
    }
}
    
    module.exports = { listUsers, ... };

lbDb, where is the configuration for database:

const Sequelize = require("sequelize");
const configs = require("./config/config");

const { initUser } = require("./models/USERS/user");
const { initSector } = require("./models/USERS/sector");
const { initArchives } = require("./models/ARCHIVES/archives");


if (Sequelize.Promise) {
    Sequelize.Promise.config({
        // Enables all warnings except forgotten return statements.
        warnings: {
            wForgottenReturn: false
        }
    });
}

const env = process.env.NODE_ENV || "development";
const config = configs[env];

if (config.logging)
    config.logging = console.log;

/**
 * @type {Sequelize} conexão com o banco de dados.
 */
let sequelize;

const db = {
    db:sequelize,

    // Carrega arquivos de modelos das tabelas.
    User: initUser(sequelize),
    Sector: initSector(sequelize),

    Archives: initArchives(sequelize)
};

Object.keys(db).forEach(modelName => {
    if ("associate" in db[modelName])
        db[modelName].associate(db);
});

module.exports = db;

user model:

const { Model, DataTypes } = require("sequelize");

class User extends Model {
    /**
     * Cria associações entre as tabelas do banco de dados.
     * @param {import("../../lbDB")} models
     */
    static associate (models) {
        User.belongsTo(models.Sector, { as: "sector", foreignKey: "id_sector" });
        User.hasMany(models.Archives, { as: "archives", foreignKey: "id_archives" });
    }
}

/**
 * Cria o modelo da tabela
 * @param {import("sequelize").Sequelize} sequelize conexão com o banco de dados.
 * @returns
 */
function initUser (sequelize) {
    User.init({
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },

        id_sector: {
            type: DataTypes.INTEGER,
            references: { model: "sector", key: "id" },
            allowNull: false
        },

        user: DataTypes.STRING(40),
        name: DataTypes.STRING(100),
        email: DataTypes.STRING(100),
        password: DataTypes.STRING(100)
    }, {
        sequelize,
        timestamps: false,
        modelName: "User",
        tableName: "user",
        underscored: true
    });

    return User;
}

module.exports = { initUser };

These are the parts of my code where I believe I might be causing an error. I can't understand why. Sequelize seems to be configured correctly, but I can't access my route or start my application without error.

CodePudding user response:

You are not initializing sequelize. Example:

const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: './user.db'
})

In your code sequelize is undefined:

let sequelize;

const db = {
    db:sequelize,

    // Carrega arquivos de modelos das tabelas.
    User: initUser(sequelize),
    Sector: initSector(sequelize),

    Archives: initArchives(sequelize)
};
  • Related