gpt4 book ai didi

node.js - Nodejs Sequelize sqlite3 没有这样的表

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

我的模型/index.js 文件:

'use strict';

const fs = require('fs');
const path = require('path');
const {Sequelize, Op, Model, DataTypes} = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});

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

db.sequelize = sequelize;
db.Sequelize = Sequelize;

db.sequelize.define('Category', {
name: {type: String, allowNull: false},
url: {type: String, allowNull: false, unique: true},
}, {
freezeTableName: true,
timestamps: true
}
);


db.sequelize.sync({ force: true }); # it should create table
module.exports = db.sequelize.models;
console.log(db.sequelize.models) # 输出:{类别:类别}
如果我对模型进行任何查询,它会抛出一个错误:
UnhandledPromiseRejectionWarning: SequelizeDatabaseError: SQLITE_ERROR: no such table: Category;
如何在数据库中插入模型?

最佳答案

您需要创建一个迁移脚本来创建表,

shell$ sequelize migration:create --name create-category-table
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Categories', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Categories');
}
};
shell$ sequelize db:migrate

关于node.js - Nodejs Sequelize sqlite3 没有这样的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66519021/

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