Daniel Saito
Daniel Saito

Reputation: 67

sequelize.sync({force:true}) not working and the logging of method is empty

I've seen a ton of questions that appears when I was writing this issue. none of them had the same problem and after 20h straight trying to solve this i'm quite stressed, so sorry if I didn't see a similar issue. Ok, the problem is the following: I'm using nodejs,expressjs(4.17),sequelize-cli(6.2.0)and sequelizejs(6.3.5) to do a server and communicate with mysql(mysql2 2.1.0) and for some reason when I use the function sequelize.sync() (having or not the {force:true}) it just doesn't update the tables inside the database, which is already created, it does nothing, no errors, no warnings, just not doing what's supposed to do. I created the models using npx sequelize model:generate --name ... --attributes ... so the migrations created does not have anything I manually inserted in it, because I searched that's not supposed to change the migrations files. Then I ran npx sequelize db:migrate to up the migrations to database and finally did some changes to models that didn't synced.

here is the server.js code:

const http = require('http')
const Sequelize = require('sequelize')
const app = require('./src/app')
const port = process.env.PORT || 3000
const server = http.createServer(app)

const contatos = require('./src/_db/models/contatos')
const corretores = require('./src/_db/models/corretores')
const imoveis = require('./src/_db/models/imoveis')
const tipoimovel = require('./src/_db/models/tipoimovel')

const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USERNAME, process.env.DB_PASSWORD, {
    host: 'localhost',
    dialect: "mysql" /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,
    logging: console.log,  
})

sequelize.authenticate().then( () => {
    console.log('Connection has been established successfully.');
    

    sequelize.sync({logging:console.log, force:true})
        .then(() => {
            // console.log(`Database & tables created!`);
            return server.listen(port)
        }).catch((error)=>{
            return console.error(error);
        });

}).catch((error) => {
    console.error('Unable to connect to the database:', error);
})

The code of my app.js:

const express = require('express')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const Sequelize = require('sequelize')
const app = express()

app.use(morgan('dev'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Accept, Authorization'
    )
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
        return res.status(200).json({})
    }
    next()
})



app.use((req, res, next) => {
    const error = new Error('Not found')
    error.status = 404
    next(error)
})

app.use((error, req, res, next) => {
    res.status(error.status || 500)
    res.json({
        error: {
            message: error.message
        }
    })
})

module.exports = app

The console result of all:

[nodemon] restarting due to changes...  
[nodemon] starting 'node server.js'    
Executing (default): SELECT 1+1 AS result     
Connection has been established successfully.     
Executing (default): SELECT 1+1 AS result     
Database & tables created! 

And finally an example of Model that I'm trying to update the database with, already with changes I've made:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class tipoImovel extends Model {
    
    static associate(models) {
      // define association here
      this.hasOne(models.Imoveis)
    }
  };
  tipoImovel.init({
    tipoNome: {type:DataTypes.STRING,allowNull:false},
    tipoSigla: {type: DataTypes.STRING(2),allowNull:false,unique:true}
  }, {
    sequelize,
    modelName: 'tipoImovel',
  });
  return tipoImovel;
};

Upvotes: 1

Views: 8111

Answers (3)

Diego Archila
Diego Archila

Reputation: 1

in my case, I am using Sequealize cli for creating the environment of settings and config. I am using the version 6.

When we are using the Sequealize cli, int the path where we are creating the model has a one file index.js only add the following line between:

db.sequelize = sequelize;
db.Sequelize = Sequelize;

/** Auto Update */
sequelize.sync({force:true});


module.exports = db;

I share the full code of the file index.js:

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf('.') !== 0 &&
      file !== basename &&
      file.slice(-3) === '.js' &&
      file.indexOf('.test.js') === -1
    );
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

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

db.sequelize = sequelize;
db.Sequelize = Sequelize;

/** Auto Update */
sequelize.sync({force:true});


module.exports = db;

For more information about the function sync(). See the documentation: https://sequelize.org/api/v6/class/src/sequelize.js~sequelize#instance-method-sync

Upvotes: 0

Jyotirmoy Upadhaya
Jyotirmoy Upadhaya

Reputation: 545

db.sequelize.sync({ force: true }).then(() => {});

Force true will turncate the table. It will definitely update the table with new column but data will be lost. It should work with alter true only

Upvotes: 0

Aryan
Aryan

Reputation: 3638

I have used sync like this, and it worked for me. You can try it as solution if you want.

'use strict';
const Sequelize = require('sequelize');
const cls = require('cls-hooked');
const namespace = cls.createNamespace('my-very-own-namespace');
Sequelize.useCLS(namespace);
const config = require("../environments/index");

// server connection settings
var db_instance = new Sequelize(config.DB.database, config.DB.username, config.DB.password, {
  host: config.DB.host,
  dialect: config.DB.dialect,
  define: {
    timestamps: false
  },
  logging: false
});

var sequelize = db_instance;

// checks the database connectivity
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });


const db = {};

db.sequelize = sequelize;
db.Sequelize = Sequelize;

// create the modal instance 
db.users = require('../model/users.model')(sequelize, Sequelize);
db.country = require('../model/country.model')(sequelize, Sequelize);
db.state = require('../model/state.model')(sequelize, Sequelize);
db.city = require('../model/city.model')(sequelize, Sequelize);
db.verify_otp = require('../model/verify_otp.model')(sequelize, Sequelize);
db.organizations = require('../model/organizations.model')(sequelize, Sequelize);
db.features = require('../model/features.model')(sequelize, Sequelize);
db.user_features = require('../model/user_features.model')(sequelize, Sequelize);
db.roles = require('../model/roles.model')(sequelize, Sequelize);
db.user_roles = require('../model/user_roles.model')(sequelize, Sequelize);



db.sequelize.sync({ force: true }).then(() => {
  console.log("Drop and re-sync db.");
});

module.exports = db;

Upvotes: 1

Related Questions