Michael
Michael

Reputation: 112

Can't create table in database using class model in Sequelize

I'm using node.js with express and sequelize and my DB is mysql. I tried to create a class model as written in the documentation: https://sequelize.org/master/manual/model-basics.html. I was able to connect to the DB, but couldn't figure out how to sync the model with the DB in order to create tables. here is my user model:

const { DataTypes, Model } = require('sequelize');
const connection = require("../server");

export class User extends Model { }

User.init({
    id: {
        type: DataTypes.BIGINT,
        autoIncrement: true,
        primaryKey: true,
        unique: true,
        allowNull: false
    },
    username: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true,
    },
    password: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    userType: {
        type: DataTypes.STRING,
        allowNull: false,
    }
}, {
    connection
});

and here is my server.js:

const express = require("express");
const Sequelize = require("sequelize");

const app = express();
const port = 8080;

const connection = new Sequelize("coupons2", "root", "1234", {
    host: "localhost",
    dialect: "mysql"
})

connection.sync()
    .then(() => {
        console.log("Connection to DB was successful");
    })
    .catch(err => {
        console.error("Unable to connect to DB", err);
    });

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
})

module.exports = connection;

Thank you!

Upvotes: 1

Views: 7513

Answers (3)

teranshil
teranshil

Reputation: 187

  • User.sync() - creates the table if it doesn't exist (and does nothing if it already exists)
  • User.sync({ force: true }) - creates the table, dropping it first if it already existed
  • User.sync({ alter: true }) - checks what is the current state of the table in the database (which columns it has, what are their data types, etc), and then performs the necessary changes in the table to make it match the model.
(async () => {
    await sequelize.sync({ alter: true });
})();

Upvotes: 1

Michael
Michael

Reputation: 112

I managed to create tables by importing the models to my server.js: const models = require("./src/models/index");, and using the sync() method.

Upvotes: -3

Aryan
Aryan

Reputation: 3638

I think you forgot to require the Sequelize as shown in document you mentioned above

`const {Sequelize, DataTypes, Model } = require('sequelize');

and if you want that it table create automatically by models you can use sequelize.sync in your project

await sequelize.sync({ force: true });
console.log("All models were synchronized successfully.");

Upvotes: 5

Related Questions