Home > other >  Sequelize synch doesn't create table in db
Sequelize synch doesn't create table in db

Time:06-20

I have project structure like

├── index.ts
├── package.json
├── package-lock.json
├── src
│   ├── controllers
│   ├── models
│   │   └── repository.ts
│   ├── routes
│   │   └── repository.ts
│   └── services
│       ├── minio.ts
│       └── sequelize.ts
└── tsconfig.json
// services/sequelize.ts
import { Sequelize } from 'sequelize'

const sequelizeConnection = new Sequelize("randomDb", "randomUser", "randomPassword", {
    host: "randomHost",
    dialect: "mysql"
})

export default sequelizeConnection
// models/user.ts
import { DataTypes } from 'sequelize'
import sequelizeConnection from '../services/sequelize'

const User = sequelizeConnection.define("user", {
    name: {
        type: DataTypes.STRING(30),
        allowNull: false
    }
})

export default User
// index.ts
import express from 'express'
import sequelize from './src/services/sequelize'

const app = express()

const startApp =  async()=> {
    try {
        await sequelize.sync()

        app.listen(3000, () => {
            console.log(`Listen on port 3000`)
        })
    } catch (error) {
        console.log("Synchronization error")
    }
}
startApp()

When I start app, "sequelize.sync()" should create table "users", but for some reasons it doesn't. I tried call sync() method separately on "User" and it worked, so there's no problem with connection with db.

await User.sync()

But in my case, I have much more models and I don't want call synch method on each model.

CodePudding user response:

I believe the issue here is just with your folder structure. The models directory should be on the same level as the index.ts.

Documentation on the .sync() method isn't great, likely because migrations are the preferred approach for production applications (Reference). It's possible there is a config attribute you can set somewhere to maintain your current structure, though I dug around a little bit and couldn't find anything.

  • Related