我在我的 Express.js 应用程序中使用 MySQL 的 sequelize。
所有数据库凭据都存储在 .env 文件中并且是正确的:
DATABASE_NAME= mydb
DATABASE_USERNAME= root
DATABASE_PASSWORD= pass
DATABASE_HOST= localhost
DATABASE_PORT= 3306
database.js 文件:
require('dotenv').config();
const Sequelize = require('sequelize');
module.exports = new Sequelize(
process.env.DATABAST_NAME,
process.env.DATABASE_USERNAME,
process.env.DATABASE_PASSWORD,
{
port: process.env.DATABASE_PORT,
host: process.env.DATABASE_HOST,
dialect: 'mysql'
}
);
在用户模型中:
const Sequelize = require('sequelize');
const db = require('../config/database');
module.exports = db.define('user', {
username: {
type: Sequelize.STRING,
unique: true,
primaryKey: true
},
email: {
type: Sequelize.STRING,
unique: true
},
password: {
type: Sequelize.STRING
},
}, {
freezeTableName: true,
timestamps: false
});
user.findAll().then(data=>{
console.log(data)
});
数据库“mydb”只有一个表“用户”,应用程序启动时,出现错误:
Executing (default): SELECT `username`, `email`, `password` FROM `user` AS `user`;
Unhandled rejection SequelizeDatabaseError: No database selected
at Query.formatError (C:\Users\me\WebstormProjects\Backend\node_modules\sequelize\lib\dialects\mysql\query.js:241:16)
at Query.handler [as onResult] (C:\Users\me\WebstormProjects\Backend\node_modules\sequelize\lib\dialects\mysql\query.js:48:23)
at Query.execute (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\commands\command.js:30:14)
at Connection.handlePacket (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\connection.js:449:32)
at PacketParser.Connection.packetParser.p [as onPacket] (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\connection.js:72:12)
at PacketParser.executeStart (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.Connection.stream.on.data (C:\Users\me\WebstormProjects\Backend\node_modules\mysql2\lib\connection.js:79:25)
at Socket.emit (events.js:189:13)
at addChunk (_stream_readable.js:284:12)
at readableAddChunk (_stream_readable.js:265:11)
at Socket.Readable.push (_stream_readable.js:220:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
我试图用下面的代码测试 .env 文件,一切都是可读的:
var config = require('dotenv').config(); 控制台日志(配置)
我试图在 db.defind() 中的“用户”前面添加数据库名称,但遇到了同样的问题。
请,如果您有任何建议,请告诉我。