question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

sequelize db:migrate does not create initial tables defined in feathersjs app model

See original GitHub issue

Steps to reproduce

  1. Setup the sequelize migration in a working feathersjs app as explained in the instruction.
  2. Add a migration file to modify the table.
  3. Configure package.json with "start": "sequelize db:migrate && node src/"

Expected behavior

When clean npm start, expect to run the migration, including creating the initial db tables and its association defined in the application model files, and then to start the application.

Actual behavior

Shows the below error: ERROR: Table ‘xxxxx.roles’ doesn’t exist npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! xxxxx@0.0.0 start: sequelize db:migrate && node src/ npm ERR! Exit status 1

This means the application start did not create the initial table schema defined in the application model files in src/models/ folder. I think I am missing something that binds migration with application.

Note: Application creates the initial tables and association when run without migration, though. Migration also completes successfully when run after the tables are created. But can’t run the migration and the application in a single go.

System configuration

Module versions (especially the part that’s not working):

DB: MySQL

@feathersjs/feathers”: “^3.3.1” “feathers-sequelize”: “^4.1.1”


app.js:

const path = require('path');
const favicon = require('serve-favicon');
const compress = require('compression');
const helmet = require('helmet');
const cors = require('cors');
const logger = require('./logger');

const feathers = require('@feathersjs/feathers');
const configuration = require('@feathersjs/configuration');
const express = require('@feathersjs/express');
const socketio = require('@feathersjs/socketio');


const middleware = require('./middleware');
const services = require('./services');
const appHooks = require('./app.hooks');
const channels = require('./channels');

const sequelize = require('./sequelize');

const authentication = require('./authentication');

const app = express(feathers());

// Load app configuration
app.configure(configuration());
// Enable security, CORS, compression, favicon and body parsing
app.use(helmet());
app.use(cors());
app.use(compress());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(favicon(path.join(app.get('public'), 'favicon.ico')));
// Host the public folder
app.use('/', express.static(app.get('public')));

// Set up Plugins and providers
app.configure(express.rest());
app.configure(socketio());

app.configure(sequelize);

// Configure other middleware (see `middleware/index.js`)
app.configure(middleware);
app.configure(authentication);
// Set up our services (see `services/index.js`)
app.configure(services);
// Set up event channels (see channels.js)
app.configure(channels);

// Configure a middleware for 404s and the error handler
app.use(express.notFound());
app.use(express.errorHandler({ logger }));

app.hooks(appHooks);

module.exports = app;

sequelize.js:

const Sequelize = require("sequelize");

module.exports = function(app) {
  const connectionString = app.get("mysql");
  const sequelize = new Sequelize(connectionString, {
    dialect: "mysql",
    logging: true,
    operatorsAliases: false,
    define: {
      freezeTableName: true,
      timestamps: false
    }
  });
  const oldSetup = app.setup;

  app.set("sequelizeClient", sequelize);

  app.setup = function(...args) {
    const result = oldSetup.apply(this, args);

    // Set up data relationships
    const models = sequelize.models;
    Object.keys(models).forEach(name => {
      if ("associate" in models[name]) {
        models[name].associate(models);
      }
    });

    // Sync to the database
    sequelize.sync();

    return result;
  };
};

migrations/config.js:

const app = require("../src/app");
const env = process.env.NODE_ENV || "development";
const dialect = "mysql";

module.exports = {
  [env]: {
    dialect,
    url: app.get(dialect),
    migrationStorageTableName: "_migrations",
    seederStorage: "sequelize",
    seederStorageTableName: "_migrations_seed"
  }
};

migrations/models.js:

const Sequelize = require("sequelize");
const app = require("../src/app");
const sequelize = app.get("sequelizeClient");
const models = sequelize.models;

// The export object must be a dictionary of model names -> models
// It must also include sequelize (instance) and Sequelize (constructor) properties
module.exports = Object.assign(
  {
    Sequelize,
    sequelize
  },
  models
);

Thanks in advance; @daffl

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
soesujithcommented, Jul 26, 2019

@daffl , Could you please help on this. Thanks

1reaction
dafflcommented, Jul 23, 2019

You can change sequelize.sync(); to app.set('sequelizeSync', sequelize.sync()); and then in a migration do

const app = require('../src/app');

const setupApplication = async () => {
  app.setup();
  return app.get('sequelizeSync');
};

module.exports = {
  async up () {
    await setupDb();
    // Do things here
  },

  async down () {
    await setupDb();
    // Do things here
  }
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

Feathersjs with Sequelize, updating the model - Stack Overflow
In your src/sequelize.(js|ts) , there should be a call like sequelize.sync() . This updates the structure of the database according to the ...
Read more >
Raw Queries - Sequelize
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use...
Read more >
Untitled
Sequelize Singular Table Name. Im new to sequelize and Im also not sure if this is the right approach. Please, first of all,...
Read more >
Build a Node.js App With Sequelize [1] - Connection & Model
In this series we will create a simple job find app using Node.js with Sequelize which is an ORM for relational databases like...
Read more >
Untitled
If the sde login role does not exist, this tool creates it and grants it ... findOne() is a sequelize model function which...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found