我是Node和Sequelize的新手,我正在建立與MySQL數據庫的連接時遇到問題。我想知道爲什麼需要Postgres依賴關係,即使將方言設置爲mysql。如果您能幫助我指出問題,我將不勝感激。NodeJS/Sequelize/MySQL - 爲什麼需要postgres依賴關係?
從packages.json
"dependencies": {
// ...
"mysql2": "1.1.2",
"sequelize": "3.27.0"
},
的辦法,我嘗試連接數據庫:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('dbName', 'dbUser', 'dbPass', {
host: 'localhost',
dialect: 'mysql'
});
sequelize.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
錯誤我面對:
Failed to compile.
Error in ./~/sequelize/lib/dialects/postgres/hstore.js
Module not found: 'pg-hstore' in ~/node_modules/sequelize/lib/dialects/postgres
@ ./~/sequelize/lib/dialects/postgres/hstore.js 3:13-33
更新1(使用
sequelize init
命令)
從模型/ index.js:
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = 'development'; //process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
而我配置/ config.json:
{
"development": {
"username": "dbUser",
"password": "dbPassword",
"database": "dbName",
"host": "127.0.0.1",
"dialect": "mysql2"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql2"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql2"
}
}
UPDATE 2
現在我看到我有一個額外的消息:
Error: The dialect mysql is not supported. (Error: Cannot find module './mysql'.)
不過,我把它安裝到node_modules
目錄的根目錄。
UPDATE 3
予取重現該問題的步驟:
create-react-app tmpApp
npm install --save mysql sequelize
npm install -g sequelize-cli
sequelize init
- 添加到
src/index.js
:var models = require('../models')
npm start
- 這個問題似乎
UPDATE 4 - 問題解決
首先感謝真的爲您的幫助!實際發生這個問題是因爲我試圖將服務器端和客戶端混合到一個應用程序中(我只是在玩)。 Sequelize和mysql模塊本身似乎不適用於瀏覽器環境。當服務器端放置在react-app之外時,所有的行爲都像預期的那樣。
你不應該需要postgres模塊。由於您使用的是「mysql2」接口,因此請確保您使用的是「mysql2」方言,而不是「mysql」。 – user3254198
當你在'models/index.js'中做'console.log(config)'時,你得到的值是多少? – AJS
@AJS,'config.use_env_variable'是不確定的,對我來說似乎是合理的,因爲我不喜歡不想使用來自環境變量但來自'config.json'的配置。我對嗎? – Mat