我有这个Sequelize Code用于连接我的数据库
var sequelize = new Sequelize('db-name', 'user', 'pwd', {
host: 'XXX.XX.XX.XXX',
dialect: 'mysql',
pool: {
max: 50,
min: 0,
idle: 1000000
},
});
我把它包装在下面的模块中
var express = require('express');
var app = module.exports = express();
var Sequelize = require('sequelize');
module.exports = function (Sequelize, DataTypes) {
return new Sequelize('db-name', 'user', 'pwd', {
host: 'XXX.XX.XX.XXX',
dialect: 'mysql',
pool: {
max: 50,
min: 0,
idle: 1000000
},
});
};
但是,当我在下面调用此代码时:
var sequelize = require('../../Connection.js');
//load model
var City = sequelize.import('../../models/City.js');
它给我一个错误说 - undefined不是一个函数。基本上,当我导入模块时它无法实例化sequelize对象
但是,当我将这些块放在一个页面中时,一切正常
我的核心要求 - 我希望在我的节点应用中使用单个连接对象。我在各种页面中模块化了Express Routes。
答案 0 :(得分:1)
Your sequelize module exports a function, which returns sequelize. You have to actually call that function
var sequelize = require('../../Connection.js')() <-- ;
Remember to cache the instance in connection.js - otherwise you get a new connection each time. You can also export the instance directly:
module.exports = new Sequelize('db-name', 'user', 'pwd', {
host: 'XXX.XX.XX.XXX',
dialect: 'mysql',
pool: {
max: 50,
min: 0,
idle: 1000000
},
});