我是Node和Sequelize的新手,我遇到了与MySQL数据库建立连接的问题。我想知道为什么即使将方言设置为mysql也需要Postgres依赖。如果你能帮我指出问题,我将不胜感激。
来自 packages.json
"dependencies": {
// ...
"mysql2": "1.1.2",
"sequelize": "3.27.0"
},
我尝试连接db的方式:
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
命令)
来自 models / 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 / 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"
}
}
<小时/> 更新2
现在我看到我还有一条消息:
Error: The dialect mysql is not supported. (Error: Cannot find module './mysql'.)
但是,我将它安装在node_modules
目录的根目录中。
<小时/> 更新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
- 出现问题<小时/> 更新4 - 问题已解决
首先,非常感谢您的帮助!问题实际上是因为我试图将服务器端和客户端混合到一个应用程序中(我刚刚玩)。 Sequelize和mysql模块本身似乎不适用于浏览器环境。当服务器端放在react-app之外时,一切都按预期运行。
答案 0 :(得分:1)
在您的数据库配置中,您必须将配置设置为要使用的其他内容。
答案 1 :(得分:0)