Sequelize sync() 不会创建所有的表模型

Posted

技术标签:

【中文标题】Sequelize sync() 不会创建所有的表模型【英文标题】:Sequelize sync() doesn't create all of the table models 【发布时间】:2020-08-28 13:33:04 【问题描述】:

我对使用 sequelize 和 node.js 还是很陌生。

我正在尝试使用 sequelize、postgres 和 node.js 在模型“user”和“post”下创建两个表。问题是,只创建了“posts”表,而根本没有创建“users”。

这是 4 个文件的代码:“models/post”、“models/user”、“app.js”和“utils/database”:

'模型/帖子':

const Sequelize = require('sequelize');

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

const Post = sequelize.define('post',
    id: 
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    ,
    title: 
        type: Sequelize.STRING,
        allowNull: false,
    ,
    content: 
        type: Sequelize.STRING,
        allowNull: false,
    ,
    tags:
        type: Sequelize.ARRAY(Sequelize.STRING),
        allowNull: false,
    

);

Post.associate = (models) => 
    Post.belongsTo(models.User, 
        constraints: true, 
        onDelete: 'CASCADE'
    );


module.exports = Post;

'模型/用户':


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

const User = sequelize.define('user', 
    id: 
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
        primaryKey: true,
    ,
    userName: 
        type: Sequelize.STRING,
        allowNull: false,
    ,
    firstName: 
        type: Sequelize.STRING,
        allowNull: false,
    ,
    lastName: 
        type: Sequelize.STRING,
        allowNull: false,
    ,
    bio: 
        type: Sequelize.STRING,
        allowNull: false,
    ,
    password: 
        type: Sequelize.STRING,
        allowNull: false,
    
)

User.associate = (models) => 
    User.hasMany(models.Post);


module.exports = User;

'app.js':

const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');

const sequelize = require('./util/database');
const graphqlSchema = require('./graphql/schema');
const graphqlResolver = require('./graphql/resolvers');

app = express();

app.use(bodyParser.json()); 
app.use((req, res, next) => 
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader(
      'Access-Control-Allow-Methods',
      'OPTIONS, GET, POST, PUT, PATCH, DELETE'
    );
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
  );

app.use('/graphql', graphqlHttp(
    schema: graphqlSchema,
    rootValue: graphqlResolver,
    graphiql: true,
    formatError(err) 
      if (!err.originalError) 
        return err;
      
      const data = err.originalError.data;
      const message = err.message || 'An error occurred.';
      const code = err.originalError.code || 500;
      return  message: message, status: code, data: data ;
    
  )
);

app.use((error, req, res, next) => 
  const status = error.statusCode || 500;
  const message = error.message;
  const data = error.data;
  res.status(status).json( message: message, data: data );
);

 sequelize.sync(force: true)
  .then(result => 
    app.listen(8080);
  )
  .catch(err => 
    console.log(err);
  );

'utils/数据库':

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

const sequelize = new Sequelize('projectname','postgres','password',
    host: 'localhost',
    dialect: 'postgres', 

);

module.exports = sequelize;

(项目名称和密码当然被替换为真实值)

【问题讨论】:

【参考方案1】:
    在 utils/database 中注册您的模型及其关联 在注册任何路由之前移动 sync 调用

实用程序/数据库

const sequelize = new Sequelize('projectname','postgres','password',
    host: 'localhost',
    dialect: 'postgres', 

);

const db = 
const models = path.join(__dirname, 'models') // path to a models' folder

fs.readdirSync(models)
  .filter(function (file) 
    return (file.indexOf('.') !== 0)  && (file.slice(-3) === '.js')
  )
  .forEach(function (file) 
    var model = sequelize['import'](path.join(models, file))
    db[model.name] = model
  )

Object.keys(db).forEach(function (modelName) 
  if (db[modelName].associate) 
    db[modelName].associate(db)
  
)

module.exports = sequelize

【讨论】:

谢谢,根据你的回答写了一些东西,它奏效了!如果你愿意,我可以分享我写的代码 :)

以上是关于Sequelize sync() 不会创建所有的表模型的主要内容,如果未能解决你的问题,请参考以下文章

Sequelize model.sync() 抛出错误

为啥 sequelize.sync() 不同步表,除非我将模态导入文件?

Sequelize 中的 .sync() 到底是为了啥?

如何停止执行(默认):DROP TABLE IF EXISTS in sequelize sync

如何将 sequelize.sync 选项强制设置为 false?

如何在 Sequelize 中正确设置自定义“通过”表?