Sequelize 创建数据库 [英] Sequelize Create Database

查看:46
本文介绍了Sequelize 创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让 sequelize 创建我尝试连接的数据库(如果它不存在)?

Is there a way to have sequelize create the database I'm trying to connect to if it doesn't exist?

我有一个原始的 MySQL 实例,但出现此错误:

I have a raw MySQL instance and I get this error back:

ER_BAD_DB_ERROR: Unknown database 'mytest'

我想处理该错误,使用我提供的凭据(或具有创建权限的一组不同的创建),然后运行 ​​CREATE DATABASE mytest.

I'd like to handle that error, use the creds I provided (or a different set of creates with create permissions), and run CREATE DATABASE mytest.

推荐答案

我可能有一个合理的解决方案.不过我相信它可以写得更干净.

I may have a reasonable solution. I am sure it could be written more cleanly though.

对于这个例子,我使用的是 Postgres,MySQL 的答案会略有不同.我大量借鉴了这个答案:node-postgres create database

For this example I'm using Postgres, the answer would be slightly different for MySQL. I'm heavily borrowing from this answer: node-postgres create database

在 database.js 中,我有以下 init 函数

In database.js I have the following init function

var Sequelize = require('sequelize'),
    pg = require('pg');

module.exports.init = function(callback) {
    var dbName = 'db_name',
        username = 'postgres',
        password = 'password',
        host = 'localhost'

    var conStringPri = 'postgres://' + username + ':' + password + '@' + host + '/postgres';
    var conStringPost = 'postgres://' + username + ':' + password + '@' + host + '/' + dbName;

    // connect to postgres db
    pg.connect(conStringPri, function(err, client, done) { 
        // create the db and ignore any errors, for example if it already exists.
        client.query('CREATE DATABASE ' + dbName, function(err) {
            //db should exist now, initialize Sequelize
            var sequelize = new Sequelize(conStringPost);
            callback(sequelize);
            client.end(); // close the connection
        });
    });
};

init 函数在调用 sequelize 之前创建数据库.它首先打开与 postgres 的连接并创建数据库.如果数据库已经存在,则会抛出我们忽略的错误.创建后,我们初始化 sequelize 并将其发送到回调.重要的是,如果数据库已经存在,它不会被覆盖.

The init function is creating the database before sequelize is called. It first opens a connection to postgres and creates the database. If the database already exists, an error will be thrown which we are ignoring. Once it is created we initialize sequelize and send it to the callback. Importantly, if the database already exists it will not be overwritten.

在 app.js 中,我接收数据库实例并将其发送给需要它的任何模块,在本例中它是通行证.

In app.js I receive the database instance and send it over to whichever module needs it, in this case it is passport.

require('./server/config/database.js').init(function(database) {
  require('./server/config/passport.js')(passport, database);
});

这篇关于Sequelize 创建数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆