Sequelize 'Dialect needs to be explicitly supplied as of v4.0.0' - node.js

I need to run third party application in node.js environment but Sequelize throws 'Dialect needs to be explicitly supplied as of v4.0.0'
I've found similar topic here Dialect needs to be explicitly supplied as of v4.0.0 but 'export NODE_ENV=development' doesn't work and I can not find Sequelize config file.
How can I fix this error?
Here is code:
const Sequelize = require('sequelize');
const scheme = require('./scheme');
const Op = Sequelize.Op;
const sequelize = new Sequelize(null, null, {
dialect: 'sqlite',
storage: 'db.sqlite3',
operatorsAliases: { $and: Op.and },
logging: false
});
scheme(sequelize);
sequelize.sync();
module.exports.sequelize = sequelize;
module.exports.models = sequelize.models;

You simply supply the dialect when you initialize sequelize;
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: // pick one of 'mysql','sqlite','postgres','mssql',
});

Node cannot find your environment to load in the config file.
You can easily fix by running this
export NODE_ENV=development; npx sequelize db:migrate
This should export to NODE_ENV the environment needed to run it.

this worked for me:
'use strict';
const path = require('path');
const Sequelize = require('sequelize');
const db = {};
const DB = 'users';
const USER = 'user';
const PASSWORD = 'password';
const HOST = 'host';
const DIALECT = 'postgres';
const PORT = 5432;
const CONNECTION = new Sequelize(
DB,
USER,
PASSWORD,
{
host: HOST,
dialect: DIALECT,
port: PORT,
}
)
module.exports.CONNECTION = CONNECTION;

I think you already have solved the problem. But I faced the same issue.
My issue had happened due to the name change of the config file that is auto generated by the sequelize-cli. So what I eventually did was, I created a .sequelizerc file in the project root folder and include following content.
const path = require('path');
module.exports = {
'config': path.resolve('config', 'database.json'),
'models-path': path.resolve('db', 'models'),
'seeders-path': path.resolve('db', 'seeders'),
'migrations-path': path.resolve('db', 'migrations')
};
Make sure to change the arguments according to your folder structure of the project.
A comprehensive explanation has on the sequelize documentation page.
https://sequelize.org/master/manual/migrations.html

Related

how to properly set up a database config file for sequelize? i keep getting "TypeError: Cannot read properties of undefined (reading 'max')"

basically, i am trying to make my app choose which database it's going to use. i'm having trouble, because i keep getting a "TypeError: Cannot read properties of undefined (reading 'max')". i've spent about three hours on this (very new to web stack stuff, so don't laugh at me please) and could really use some assistance. thanks in advance.
db.config.js.
it doesn't work with pool active either, so don't mind that.
require('dotenv').config();
module.exports = {
dev: {
HOST: "localhost",
USER: "postgres",
PASSWORD: "redacted",
DB: "testtest",
//dialect: "mysql"
dialect: "postgres"
}, // pool was here, removed it to make the whole thing smaller
production:{
// empty until i get actual production values from my hosting service
}
}
index.js
const env = process.env.NODE_ENV || 'dev';
const config = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(
config.DB,
config.USER,
config.PASSWORD,
{
host: config.HOST,
dialect: config.dialect,
operatorsAliases: false,
pool: {
// omitted to make example smaller
}
}
);
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
// ...models relationships defined here
module.exports = db;
to my understanding,
const env = process.env.NODE_ENV || 'dev';
means that if a value isn't present within my .env file (it isn't), it will default to 'dev' settings, and connect to my local database.
const config = require("../config/db.config.js");
this is here so the file can access those values.
i tried making an entirely separate file for environment configuration, but it gave me a sequelize error (that i can't pull up right now). this is what i had before:
const dbEngine = process.env.DB_ENVIRONMENT || 'dev';
const config = require('./db.config')[dbEngine];
module.exports = require('sequelize')(config);

TypeError: _stream.Readable.from is not a function in sequelize node js

I am getting the below error when I am trying to establish a database connection in my node js application using sequelize
C:\Users\user123\Desktop\project\node_modules\tedious\lib\token\token-stream-parser.js:24
this.parser = _stream.Readable.from(_streamParser.default.parseTokens(message, this.debug, this.options));
^
TypeError: _stream.Readable.from is not a function
I am in initial stage of creating an application. Where I have just tried to create a database connection, for which I have created three files
index.js
var dotenv = require("dotenv").config().parsed;
var customEnv = require("custom-env");
customEnv.env("development").env();
var express = require("express");
const helmet = require("helmet");
var cookieParser = require("cookie-parser");
const app = express();
app.use(helmet());
app.use(cookieParser());
require("./db.js");
httpserver = require("http").createServer(app);
httpserver.timeout = 0;
httpserver.listen(3457, async () => {
connectedEmitter.on("connectedDbs", () => {
console.log(` ----- SERVER LISTENING ON PORT `);
});
});
db.js
const Sequelize = require('sequelize');
const eventEmitter = require('events');
global.connectedEmitter = new eventEmitter()
global.sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
port: 1433,
dialect: process.env.DB_DIALECT,
ssl: false,
dialectOptions: {
ssl:false
},
logging:false,
pool: {
max: 20,
min: 0,
idle: 30000
}
});
sequelize.authenticate().then(() => {
console.log(`${process.env.DB_NAME} - Connection has been established successfully.`);
global.connectedEmitter.emit('connectedDbs')
}).catch((err) => {
console.error(' - Unable to connect to the database:', err);
});
.env (I am giving dummy credentials as I cannot provide original credentials)
# ################################## Database Credentials ##############################################
DB_NAME=mydb
DB_USER=username
DB_PASS=password
DB_HOST=hostname
DB_DIALECT=mssql
Can anyone please tell me why am I getting the error mentioned. Where have I made the mistake in setting the database connection. Please help.
I also faced this issue. Turns out tedious had issues with node versions below 12, and my production app service was running on node 10.
GitHub link that mentions this

Sequelize Migration Error: Dialect needs to be explicitly supplied as of v4.0.0

This is my config.js file
require('dotenv').config();
module.exports = {
test: {
username: process.env.DB_USER_2,
password: process.env.DB_PASS_2,
database: process.env.DB_TABLE,
host: process.env.DB_HOST_2,
dialect: "mysql"
},
production: {
username: process.env.DB_USER_PRODUCTION,
password: process.env.DB_PASS_PRODUCTION,
database: process.env.DB_TABLE_PRODUCTION,
host: process.env.DB_HOST_PRODUCTION,
dialect: "mysql"
}
}
This is my index.js file within my models folder
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.js')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
console.log(process.env)
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
I have a .env file with the current environment of testing, I'm trying to run a migration right now, Right now I emptied the migration file incase anything there was messing up the sequelize. When I run db:migrate:status it throws the error about the database dialect. Does anyone know why the dialect error gets thrown?
The issue i faced with this was that the index file was set for development, yet there was no development option in my config.js, the issue went away once I updated that.
Update your example to look like this:
require('dotenv').config();
module.exports = {
development: {
username: process.env.DB_USER_2,
password: process.env.DB_PASS_2,
database: process.env.DB_TABLE,
host: process.env.DB_HOST_2,
dialect: "mysql"
},
test: {
username: process.env.DB_USER_2,
password: process.env.DB_PASS_2,
database: process.env.DB_TABLE,
host: process.env.DB_HOST_2,
dialect: "mysql"
},
production: {
username: process.env.DB_USER_PRODUCTION,
password: process.env.DB_PASS_PRODUCTION,
database: process.env.DB_TABLE_PRODUCTION,
host: process.env.DB_HOST_PRODUCTION,
dialect: "mysql"
}
}
update your config file and you should be good to go.

Connections to postgres database failure

I am trying to implement an auth service using node-express-postgres.
I had the pool configed as such:
const Pool = require('pg').Pool;
const pool = new Pool({
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: 5432
});
module.exports = pool;
I am trying to do the following call as a simple test for connection:
const express = require('express');
const router = express.Router();
const pool = require('../db');
const bcrypt = require('bcryptjs');
router.post('/login', async (req, res) => {
try {
let temp = await pool.query("SELECT * FROM records");
console.log(temp)
} catch (error) {
console.log(error.message);
}
});
When I send a post request to this endpoint my app crash with the following error:
Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string
I have checked all my env vars and they are correct.
Any idea why it is failing to do any operation on the postgres DB?
It seems, that node didn't read .env file.
You can check it with
console.log(process.env.DB_PASSWORD);
It can be fixed with package 'dotenv', for example.
npm i --save dotenv
And then in first line in index.js
require('dotenv').config();
For me configuring 'dotenv' resolved error
require('dotenv').config();
Check your postgres password if it's correct. I had a similar problem while working on a mac, by default the
posgreSQL user is "posgres" and password is "root"
In my case I had something like
...
USER: "postgres",
PASSWORD: "",
...
which generated the error
you probably should indicate your .env file location inside of the config
require('dotenv').config({ path: '../.env' });
dotenv configurations
Fixed it by updating npm script.
cross-env NODE_ENV=development nest start
Installed "cross-env" to set NODE_ENV.
If our code is not able to find .development.env file or unable to find password, then this error will be thrown.
Check out the path in your IDE folder, when i checked, it was by one path below, so i moved it in the correct folder and boom, it all worked.

Sequelize migration in Heroku Postgres: Chain of errors

My express.js app is on a heroku dyno. I created some rest api endpoints for crud operations (connected to heroku-postgres db) and checked they worked with Postman.
My problems have started after I tried incorporating migrations. I am just a jr. dev so please let me know if I am investigating dead leads, and what other information to provide to properly diagnose these error messages.
Starting migrations with sequelize model:create --name tableName --attributes ... was fine.
When running sequelize db:migrate, the error I get is:
ERROR: Dialect needs to be explicitly supplied as of v4.0.0
My current config.json is
{
"production": {
"use_env_variable": "DATABASE_URL",
"dialect": "postgres",
"dialectOptions": {
"ssl": {
"require": true
}
},
"ssl": true
}
}
and I have also specified the dialect in models/index.js (this was generated along with config.json in the sequelize model:create... command)
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = 'production' || process.env.NODE_ENV;
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
const sequelize = new Sequelize(process.env.DATABASE_URL, {
logging: false,
dialect: "postgres",
dialectOptions: {
ssl: true,
}
});
// 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);
// }
If const sequelize = ... is commented out, and let sequelize; ... is used instead, the same dialect error occurs.
Interestingly, when I set the shell variable export NODE_ENV=production, a new error occurs - ERROR: Error parsing url: undefined.
This is more baffling to me as I thought it was already defined in the const env = ... line in index.js.
So then I tried specifying url in the migration command - sequelize db:migrate --url 'postgres://username:password#localhost/test1'.
This url that I have provided worked for the CRUD testing via Postman, as well as via the front-end collecting the form data.
Now the error is ERROR: connect ECONNREFUSED 127.0.0.1:5432. I am unsure how to proceed from this point, and not sure that the steps I have taken since the dialect error are the correct ways to fix these problems.
My questions really are the cause of these errors.
1) Where else do I need to specify dialect?
2) Why does the dialect error go away when I export NODE_ENV, even though the environment is already specified in index.js?
3) Similarly for the url, why won't url from my .env brought in with require('dotenv').config() be accepted?
It was all well and good to generate migration and model files using the sequelize-cli. I had pushed these changes to heroku but was running the migration commands locally. (I do not have a local dev database, my only environment is production).
Another problem was, the heroku bash ran in what I can only describe as a snapshot of the application's state when heroku run bash is run. This meant that even though I was creating, editing, and pushing just fine, the migration commands would be 'stuck' on the old version until the bash was restarted.

Resources