Error creating a table with sequelize "Typeerror: Cannot read Property 'sequelize' of Undefined"

Asked

Viewed 404 times

1

I have the following error when trying to create a table:

const Usuario = app.db.sequelize.define('user', {

Typeerror: Cannot read Property 'sequelize' of Undefined

My folder structure:

inserir a descrição da imagem aqui

My configuration file ( server.js )

module.exports = function(){
    var express = require("express");
    var consign = require("consign");
    var app = express();

    consign({ cwd: "app" }).include("routes").then("config/db.js").then("controller").then("model").into(app);



    return app;
}

My db.js

var sequelize = require("sequelize");
const db = new sequelize("william", "root", "root", { host: "localhost", dialect: "mysql",  operatorsAliases: false });
module.exports = db;

My index.js

var app = require("./app/config/server")();

app.listen(3000, function(){
    console.log("Rodando na porta 3000");
});

And my model is in trouble

module.exports = function(app){
    const Usuario = app.db.sequelize.define('usuario', {
        nome: Sequelize.STRING,
        endereco: Sequelize.STRING
    });
}

Note: I am using the express: 4.16.2, cosign: 0.1.6, mysql2: 1.5.1, sequelize: 4.32.3

  • try to change the injection of the consign where it is then("config/db.js") for then("config")

  • @Lucascosta he enters an infinite loop.

  • leaves the server.js at the root and not inside the config folder and changes the path used in index.js

  • @Lucascosta unfortunately the error persists the same.

  • In your db.js, try placing module.Exports = {db: db}

1 answer

1


I think I found where your problem is, I also suffered a lot when going to use Sequelize and not Mongoose, your error is in the file db.js, ali vc need to import 2 instances of sequelize when I set up the sequelize I do this way, I will use the data you put in the question to be clearer for you.

Possible solution:

const Sequelize = require('sequelize');
const sequelize = new Sequelize({
    database: 'willian',
    username: 'root',
    password: 'root',
    host: 'localhost',
    dialect: 'mysql',
    operatorAliases: false
})

module.exports = {
    Sequelize: Sequelize,
    sequelize: sequelize
}

Note that there are 2 types of calls from Sequelize it in upper and lower case

And in the model you can declare as follows:

const db = require('../config/db')   //path de onde salvou seu db.js

const User= db.sequelize.define('users', {
    name: {
        type: db.Sequelize.STRING,
        allowNull: false,
    },
    years: {
        type: db.Sequelize.INTEGER,
        allowNull: false
    },
    birthday: {
        type: db.Sequelize.DATE,
        allowNull: false
    },
})

module.exports = User

Don’t forget to give one ({force: true}) to create the table

any question please comment, hope you helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.