I can not find a solution why, I can not connect to the database, please tell me where my mistake
I try to output whether the database is connected or not, but I get an error
index:
const fs = require("fs");
const path = require('path');
const { sequelize } = require("sequelize");
const { connection } = require('connection');
sequelize
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
connection:
require('dotenv').config()
const fs = require("fs");
const Sequelize = require("sequelize");
module.exports = connection = {
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.HOST_DB,
dialect: "mysql",
timezone: "+03:00",
dialectOptions: {
charset: "utf8mb4",
},
logging: false
};
module.exports = {
development: connection
};
error:
.authenticate()
^
TypeError: Cannot read properties of undefined (reading 'authenticate')
Related
I was trying to perform postgres queries using node but for some reason is not fetching the data from postgres.
See my database.js below:
const { Client } = require('pg');
const PORT = process.env.PORT || 3000;
const client = new Client({
host: 'localhost',
port: PORT,
user: 'postgres',
password: 'postgres',
database: 'ecommerce'
})
client.connect();
client.query('select * from customers', (err, result) => {
if (!err) {
console.log(result.rows)
} else {
console.log(err)
}
client.end();
})
Please note that the customers table is a valid table in my ecommerce database.
Any help would be appreciated.
You should wait the client to connect.
See the docs here
const { Client } = require('pg')
const client = new Client()
client
.connect()
.then(() => console.log('connected'))
.catch(err => console.error('connection error', err.stack))
Instead of console.log('connected'), write your query.
I'm trying to connect from nodeJS to Sql Server on my local machine. When I run the app the following error is raised:
Login failed for user \'admin\'.', code: 'ELOGIN' },
Here's my connection details:
const sql = require('mssql');
const config = {
host:'localhost',
user:'admin',
password:'password',
database:'database',
server:'localhost\\SQLEXPRESS'
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to localhost '+ config.database +' database');
return pool;
})
.catch(err => console.log('Database connection failed. Error: ', err));
module.exports = {
sql, poolPromise
}
This PoolPromise is then used in some Repository files to manage the data from database like this:
const { poolPromise } = require('./pool');
module.exports = {
create: async function (name) {
const pool = await poolPromise;
return await pool.request()
.input('nameParameter', name)
.query('INSERT INTO dbo.table(nombre) VALUES (#nameParameter)')
.then(result => {
console.log(result);
}).catch(function(err) {
console.log(err.message);
});
},
I've tried installing the msnodesqlv8 module, but it's not working. My npm version is npm: '6.4.1'.
I'm losing my mind trying to solve this. Any ideas?
const sql = require('mssql')
const config = {
user: 'root',
password: 'root',
server: 'localhost',
database: 'test'
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
module.exports = {
sql, poolPromise
}
const express = require('express')
const router = express.Router()
const { poolPromise } = require('./pool')
router.get('/', async (req, res) => {
try {
const pool = await poolPromise
const result = await pool.request()
.input('input_parameter', sql.Int, req.query.input_parameter)
.query('select * from mytable where id = #input_parameter')
res.json(result.recordset)
} catch (err) {
res.status(500)
res.send(err.message)
}
})
module.exports = router
Please use instance and server
dialect: 'mssql',
port: 1433,
options: {
// If you are on Microsoft Azure, you need encryption:
encrypt: true,
database: process.env.SQL_DATABASE , //update me
instanceName: process.env.SQL_INSTANCE
}
My app is able to connect to MongoDB locally but on heroku logs i'm getting this error:
Error: Invalid schema, expected mongodb or mongodb+srv
This is what my connection to mongodb looks like in my server.js file:
// // DB config
const db = require("./config/keys").mongoURI;
// // Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
config/keys:
if (process.env.NODE_ENV === "production") {
module.exports = require("./keys_prod");
} else {
module.exports = require("./keys_dev");
}
keys_dev:
module.exports = {
mongoURI:
"mongodb://jenn123:jenn123#devconnect-shard-00-00-acrk4.mongodb.net:27017,devconnect-shard-00-01-acrk4.mongodb.net:27017,devconnect-shard-00-02-acrk4.mongodb.net:27017/test?ssl=true&replicaSet=devconnect-shard-0&authSource=admin&retryWrites=true",
secretOrKey: "secret"
};
keys_prod:
module.exports = {
mongoURI: "process.env.MONGO_URI",
secretOrKey: "process.env.SECRET_OR_KEY"
};
Any help is greatly appreciated
Well, you're doing the production keys wrong.
process.env is an object containing the env variables as key and their values.
so instead of putting them in a string, you gotta remove the string and treat it as an object. like below:
module.exports = {
mongoURI: process.env.MONGO_URI,
secretOrKey: process.env.SECRET_OR_KEY
};
This is typically how I connect with mongoose.
const mongoose = require('mongoose');
const dotenv = require('dotenv').config();
let db = mongoose.connection;
mongoose.connect('your connection URL here', {
auth: {
user: "Your username",
password: "Your password"
}
})
.then(() => {
console.log('connection successful')
db = mongoose.connection;
module.exports = db;
})
.catch((err) => {
console.error(err)
});
You can then use it in a file like so (this is assuming you've defined a job schema and are importing it):
const db = require('./db'); // provides the mongoDB connection
const mongoose = require('mongoose');
const ObjectId = require('mongoose').Types.ObjectId;
const Job = require('./schemas/jobs').Job
module.exports.createJob = function (newJob) {
const job = new Job(newJob);
return new Promise((resolve, reject) => {
job.save((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
I'm having some problem using Sequelize, this is my code:
index.js
import {initializeSequelize} from "./config/sequelize_init"
async function main() {
try {
let db = await initializeSequelize();
console.log("DB Connected");
app.listen(3000, function() {
console.log("Example app listening on port 3000!");
const UserModel = require('./api/v1/user/model')
UserModel.create({fname: "a", lname: "a"});
});
} catch (error) {
console.warn(error);
}
}
main();
sequelize_init.js
import Sequelize from 'sequelize'
export async function initializeSequelize() {
const sequelize = new Sequelize(process.env.MYSQL_NAME, process.env.MYSQL_USER, process.env.MYSQL_PASS, {
host: process.env.MYSQL_HOST,
dialect: 'mysql',
port: process.env.MYSQL_PORT,
operatorsAliases: false
});
const models = {
User: sequelize.import('../api/v1/user/model.js')
};
Object.keys(models).forEach(key => {
if ('associate' in models[key]) {
models[key].associate(models);
}
});
models.sequelize = sequelize;
models.Sequelize = Sequelize;
let a = await models.sequelize.authenticate();
}
model.js
module.exports = (sequelize, Sequelize) => {
return sequelize.define('user', {
fname: Sequelize.STRING,
lname: Sequelize.STRING
});
}
This is the log when I start the server:
Executing (default): SELECT 1+1 AS result (<<<--- I DONT KNOW WHAT IS THIS BTW)
DB Connected
Example app listening on port 3000!
UserModel.create({ fname: "a", lname: "a"});
^
TypeError: UserModel.create is not a function
Can someone help me?
I guess you'd have to access the user model after requiring models.
I am new to sequelize. I am trying to use row query, but I'm getting an error.
Code:
const sequelize = require('sequelize');
sequelize.query("SELECT * from users").then(results => {
console.log(results);
})
Error while calling this API:
(node:2380) UnhandledPromiseRejectionWarning: TypeError: sequelize.query is not a function
at Promise (C:\NodejsProject\mars\app\schedule\models\schedule.js:247:17)
at new Promise (<anonymous>)
How can I fix this?
You can't use sequelize directly from require('sequelize'); ,
first we need to create instance of that , and instance will be
created from DB details , so sequelize can know on which platform ,
which DB it has to run the query
Here is the basic snippet , just for a idea :
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
// SQLite only
storage: 'path/to/database.sqlite',
// http://docs.sequelizejs.com/manual/tutorial/querying.html#operators
operatorsAliases: false
});
sequelize.query("SELECT * from users").then(results => {
console.log(results);
});
For more detail : DO READ
If you are running your db config in external file AND want and extra layer to protect from SQL injection
./database/dbs.js
const Sequelize = require('sequelize')
const db = {}
const sequelize = new Sequelize('dbname',
'username',
'password', {
host: 'localhost',
dialect: 'mysql',
logging: console.log,
freezeTableName: true,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
then in the file you want to use:
const db = require('../database/db')
...
const newDbName = 'myNewDb'
db.sequelize.query(`CREATE DATABASE IF NOT EXISTS ${newDbName} `, {
type: db.sequelize.QueryTypes.CREATE
}).then( () => {
res.send('ok done creating ' + req.body.newDbName).end()
}).catch( err => {
res.status(500).send('Err executing command ' + err).end()
})
dbConnect.js:
const Sequelize = require('sequelize');<br/>
const con = new Sequelize.Sequelize(<br/>
'db',
"user",
"password",
{
host: "localhost",
dialect: "mysql",
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
},
);
con.query("SELECT 1", (err, rows) => {
console.log(rows)
if (err) throw err;
console.log(err)
}).then(function (result){
console.log("inventory")
console.log(result)
});
module.exports = con;
// import
let con = require("../common/dbConnect")
// use in function
const [results, metadata] = await con.query(
"SELECT * FROM officer JOIN user ON officer.UserID = user.UserID"
);
console.log(JSON.stringify(results, null, 2));