我正在创建一个Nodejs MySQL数据库网站。我已经决定了一堆表需要什么模式。截至目前,我正在使用mysql工作台创建表并连接到mysql数据库。我是否应该将所有创建表模式存储在Nodejs中的某个文件夹中,然后使用node和mysql包运行它?我是否应该使用它在生产环境中创建新表,因为我会经常擦除所有数据?在网上,我很少能找到通常的操作方法。
任何建议将不胜感激
答案 0 :(得分:1)
以前,您所有的担忧都已经通过数据库迁移概念得到了解决。
数据库迁移负责使用表初始化架构。它还负责生产。
签出db-migrate。它是node.js中流行的数据库迁移工具。
它可以帮助您创建自动化脚本。 另外,请查看此excellent tutorial以获得逐步指南
答案 1 :(得分:1)
Knex是数据库迁移的良好解决方案:
您必须在knexfile.js
上建立环境连接/数据库:
var knex = require('knex')({
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test'
},
migrations: {
directory: 'migrations'
}
});
然后在/migrations
创建所需的初始表:
exports.up = function(knex) {
return knex.schema
.createTable('user', function (table) {
table.increments('id');
table.string('first_name', 255).notNullable();
table.string('last_name', 255).notNullable();
})
.createTable('product', function (table) {
table.increments('id');
table.decimal('price').notNullable();
table.string('name', 1000).notNullable();
});
};
exports.down = function(knex) {
return knex.schema
.dropTable("product")
.dropTable("user");
};
要创建表,请使用以下命令:
$> knex migrate:latest
查找更多信息