"sequelize": "^6.3.5"
server.js
const {sequelize} = require('./models/index');
async function databaseConnection() {
console.log(`Checking database connection...`);
try {
await sequelize.authenticate();
//await sequelize.sync({ force: true });
console.log('Database connection OK!');
} catch (error) {
console.log('Unable to connect to the database:');
console.log(error.message);
process.exit(1);
}
}
async function init() {
await databaseConnection();
app.listen(3000, err => {
if (err) {
console.log('============================ERROR============================');
console.log(err);
console.log('============================ERROR============================');
throw err
}
console.log(`server listening on ${app.server.address().port}`)
});
//..............................
}
init();
/models/index.js
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.forEach(file => {
if (file.indexOf('.') !== 0 && file.slice(-8) === 'Model.js') {
try {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
} catch (e) {
console.log('================ERROR====================');
console.log(path.join(__dirname, file));
console.log(e);
console.log('===========================================');
}
}
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
это пример с рабочего проекта