我正在使用MySQL在Express.js应用程序中使用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(); console.log(config)
我试图在db.defind()中的'user'前面添加数据库名称,但遇到了同样的问题。
请,如果您有任何建议,请告诉我。
答案 0 :(得分:-1)
dotenv
安装 npm
包:npm install dotenv
dotenv
文件中要求 main.ts
:import * as dotenv from "dotenv";
dotenv.config();