9

I'm learning node.js and sequelizer and I encountered a problem, i.e. I created a User model using Sequelizer, unfortunately when i want to run in index.js sequelizer.sync (); it in the console shows me the result, but it does not create a table.

My model:

const Sequelize = require('sequelize');

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

const User = sequelize.define('user', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true
    },
    name: {
        type: Sequelize.TEXT,
        allowNull: false
    },
    surname: {
        type: Sequelize.TEXT,
        allowNull: false
    }
});

module.exports = User;

my database config

const Sequelize = require('sequelize');
const sequelize = new Sequelize('node-nauka', 'root', '', {
    dialect: 'mysql',
    host: 'localhost'
});

module.exports = sequelize;

index.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const defaultRoutes = require('./routes/default');
const sequelize = require('./util/database');

app.use(bodyParser.json());

app.use(defaultRoutes);
sequelize.sync().then(result => {
    console.log(result);
    app.listen(3000);
}).catch(err => {
    console.log(err);
});

Sync result: https://pastebin.com/rtxqkMtx I miss ideas, tried on several databases and the same effect, no error but also does not create a table.

2
  • Instead of the sync method, have you tried using migrations? Commented Apr 3, 2019 at 20:37
  • No, I'm doing everything according to the NodeJS course - The Complete Guide Maximilian Schwarzmüller on udemy, everything works well with him, I do not create a table with me. Generally, I have created a database and now I wanted to create tables automatically. Commented Apr 3, 2019 at 20:44

10 Answers 10

13

In my case i just import Model to app.js

const sequelize = require("./src/Utils/database");
const User = require("./src/models/User");

sequelize
  .sync()
  .then((result) => {
    console.log(result);
  })
  .catch((err) => {
    console.log(err);
  });

@PawelC your code is same as mine so it will also work for you

Thanks

Sign up to request clarification or add additional context in comments.

Comments

9

First, you didn't show us your ./routes/default. Do you use there your model? If not, here is the error. In output on pastebin you can see:

  models: {},
  modelManager: ModelManager { models: [], sequelize: [Circular] },

Make a use of model in route and you will see:

  models: { user: user },
  modelManager: ModelManager { models: [ user ], sequelize: [Circular] },

Second, requires in your code are a little spaghetti. In index.js you require ./util/database, in ./models/user (for example) you require ./util/database, so flow is:

index.js < ./util/database > ./models/user

so as you can see, there is no flow in one direction of requires - index.js knows nothing about your model. Require is import statement, not injection of code.

If you will make usage of model in route, flow will be:

index.js < ./util/database > ./models/user > ./models/default > index.js

so there will be flow from model to index.js.

Ultimate solution

To be more comprehensive you can collect your database config and all your models in one collection (mostly in ./models/index.js so you can get it by require('./models')), and from this collection import to sync() and to routes to make use of it. Flow:

(config and models) > ./models/index.js > migrate.js > sync()
(config and models) > ./models/index.js > (routes) > index.js

Second best practice is to not use sync() in main application file (for you: index.js). Now, when you develop it's not so important, but on production this can break data in your database (drop rows for example). Better approach is use it as migrations.

Samples for this subjects you can see on our sample blog app: https://github.com/OptizeTeam/blog-api-node

1 Comment

Great! It worked for me
4

just import the user model file in index.js .This will create the table in database, as unless and until node reads that file it doesnot know that a table is created.

Comments

3

To solve this challenge, install sequelize-cli on your console. Then follow these steps below,

  1. Run npx sequelize init on your console, it generates some folders like config folder, models folder, etc. Delete the config folder and open the models -> index.js and refactor the code this way:

`

"use strict";
 const Sequelize = require("sequelize");
  const sequelize = new Sequelize("DATABASE NAME ", "USERNAME", "PASSWORD", {
  dialect: "mysql"
});

const models = {
  Product: sequelize.import("./Product") // kindly import the model created in the same folder in this manner and import more models name been created
};

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

models.sequelize = sequelize;
models.Sequelize = Sequelize;
module.exports = models;
`

2. In the same model folder where models are created, kindly refactor your model creation code this way

const sequelize = require("../util/database") // import the Database connection path;

module.exports = (sequelize, DataTypes) => {
  const Product = sequelize.define("product", {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
      allowNull: false
    },
    name: {
      type: DataTypes.STRING,
      unique: true
    },
    email: {
      type: DataTypes.STRING,
      unique: true
    },
    password: DataTypes.STRING
  });

  return Product;
};
  1. In your index.js file

`

    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    const defaultRoutes = require('./routes/default');
    const sequelize = require('./util/database');
    const models = require("./models");  // add your models folder created (Index.js)

    app.use(bodyParser.json());

    app.use(defaultRoutes);

    // Add models.sequelize script

    models.sequelize.sync({ force: true }).then(result => {
        console.log(result);
        app.listen(3000);
    }).catch(err => {
        console.log(err);
    });

`

  1. Then run your code -> npm start to get your table created. Thank you.

1 Comment

I don't understand why an ORM would delete your data every time you start it unless you explicitly ask it to do so. I have read that you can pass {force: false }, but even this doesn't work for me. It still deletes data.
1

I think the reason your code won't work is because you don't have something imported from the 'models' folder. Max has in the admin.js file from 'controllers' folder this import: const Product = require('../models/product'); and this way he linked the models folder to the rest of the app and thus allowing Sequelize to find his configuration for the model defined in the 'models' folder.

If you try to move all the code from user.js into app.js or index.js and try syncing then, you will see that will work.

Comments

1

In index.js

Import the models.

eg:-

const Product = require('./models/product');
const User = require('./models/user');

after:-

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

Code will look something like this:-

const sequelize = require('./util/database');
const Product = require('./models/product');
const User = require('./models/user');

Comments

1

Make sure that you are importing and using that Model somewhere in the code. This could be in index/app.js, or any controller.

If the model is defined but not imported somewhere else, the table will not be created.

const sequelize = require('./util/database');
const Order = require('./models/order');
const Customer = require('./models/customer');

3 Comments

Seems to me that this answer adds nothing new to the other answers to this question. There are already several answers here, you need to add new information to this.
@jmarkmurphy When you encounter a question with numerous answers, many of which share the same solution, but there is no top answer, what should people do? Should they stay quiet, or should they share that those same or mutual solutions worked for them?
Up vote the good answers, don't clutter the site with me too answers.
0

I was also following Maximilian's Udemy Course, what worked for me is that i created a post request (even though the sync didn't create table), and when i had the logic of creating a entry in one of the post routes and i started the node server, it automatically created the table.

Comments

0

Make sure the code is imported in some way or connected to the main application through other files.

Eg if a model is imported in controller that controller is then imported in routes and that routes is imported in app.js, then also in that way it will work...

Comments

-1

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JQuery Select Option</title>
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
  <script>
    $(function () {
      $("#currency_selector").selectmenu();
      $("#currency_selector2").selectmenu();
    });
  </script>

  <style>
    label {
      display: inline-block;
    }
    .ui-widget {
      display: inline-block;
      overflow: hidden;
      color: black;
      background-color: white;
    }
    .ui-selectmenu-open {
      max-height: 180px;
      overflow-y: scroll;
    }
    .fieldSpace {
      margin-top: 10px;
      margin-bottom: 50px;
    }
  </style>
</head>

<body>
  <div>
    <label for="currency_selector">Currency:</label><br>
    <select id="currency_selector" class="fieldSpace"><br>
      <option disabled>Popular Currencies</option>
      <option value="EUR">Euro (€)</option>
      <option value="USD">US Dollar ($)</option>
      <option value="GBP">UK Pound Sterling (£)</option>            
    </select>
    <br><br>
    <label for="currency_selector2">Currency:</label><br>
    <select id="currency_selector2" class="fieldSpace"><br>
      <option disabled>Asian Currencies</option>
      <option value="SGD">Singapore Dollar ($)</option>
      <option value="MYR">Malaysian Rinngit (RM)</option>
      <option value="IDR">Indonesian Rupiah (R)</option>            
    </select>        
  </div>
</body>

</html>

1 Comment

Users find it difficult to understand code only answers with no explanation. Please consider adding some description explaining how it solves the problem or add comments in the source code at appropriate places.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.