我可能有一个合理的解决方案。我相信它可以写得更干净。
对于这个示例,我使用的是 Postgres,对于 MySQL,答案会略有不同。我从这个答案中大量借用:node-postgres create database
在 database.js 中我有以下初始化函数
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 并将其发送到回调。重要的是,如果数据库已经存在,它不会被覆盖。
在 app.js 中,我接收数据库实例并将其发送到需要它的任何模块,在本例中是护照。
require('./server/config/database.js').init(function(database) {
require('./server/config/passport.js')(passport, database);
});