gpt4 book ai didi

node.js - Sequelize sync() 不会创建所有的表模型

转载 作者:行者123 更新时间:2023-12-03 22:25:48 25 4
gpt4 key购买 nike

我对使用 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);
});


“实用程序/数据库”:
const Sequelize = require('sequelize').Sequelize;

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

});

module.exports = sequelize;

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

最佳答案

  • 在 utils/database
  • 中注册您的模型及其关联
  • 在注册任何路由之前移动 同步 调用

  • 实用程序/数据库
    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

    关于node.js - Sequelize sync() 不会创建所有的表模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61756309/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com