Sequelize and MySQL with MAMP, I get an error - mysql

I get a problem with Sequelize for Express (node.js). I try to connect an MySQL database from MAMP Mac with Sequelize for express but it doesn't work, I don't understand why but I got an error:
Maybe I have to edit the MySQL configuration file for comment "MAMP_skip-networking_MAMP" but I don't find the MySQL Conf file for MAC...
My code:
var Sequelize = require("sequelize");
var db = new Sequelize('express', 'root', 'root', {
host: '127.0.0.1',
port: '3306'
});
var Project = db.define('Project', {
date: Sequelize.DATE,
title: Sequelize.STRING,
description: Sequelize.TEXT
});
var project = Project.build({
date: new Date(),
title: 'Mon premiéé projeétçç!!',
description: 'dsqlmdskq lkqskl ksqlmk lsmdqklm'
});
project
.save();

Try using port 8889 instead of 3306.

try this:
var Sequelize = require("sequelize");
var db = new Sequelize('express', 'root', 'root', {
host: '127.0.0.1',
port: '3306'
});
var Project = db.define('Project', {
date: Sequelize.DATE,
title: Sequelize.STRING,
description: Sequelize.TEXT
});
db.sync().success(function() {
var project = Project.build({
date: new Date(),
title: 'Mon premiéé projeétçç!!',
description: 'dsqlmdskq lkqskl ksqlmk lsmdqklm'
});
project.save();
})

Related

Add Data in Mongodb and Mysql in single button click

In this application i am adding data in mongodb which is working fine but at same time i need to implement Mysql. So when i register a user it should get save in Mongodb and in Mysql. My Code for Mysql Data Connection is sucessfull but data pushing is not happening(Mysql). Can anyone help me out yr. Thank you very much.
const {Sequelize} =require('sequelize');
const mysql= require('mysql');
var path1 = require('path');
var root_path = path1.dirname(require.main.filename);
var models = require(root_path+'/models');
router.post("/users", function(req, res) {
console.log("First In");
var user_id=req.query.user_id
var flag;
var userData = [];
var body_data =req.body.data;
//Mysql Start
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'tcexam'
});
con.connect((err) => {
if(err){
console.log('Error connecting to Db',err);
return;
}
console.log('Connection established');
});
models.userMysl.find({
email: body_data.email.toLowerCase()
})
console.log("Email---------->>>",email);
.then(function(country){
models.userMysl.create({
name: body_data.user_firstName,
lastname : body_data.user_lastname,
mother_name : body_data.motherName,
surname : body_data.Surname,
email: body_data.userEmail.toLowerCase(),
username:body_data.user_name,
password:body_data.user_password,
}).then(function(user) {
if(error){
console.log("Error",error);
}else {
res.send({
status: 200,
data:userData
});
}
});
});
});
//Mysql End
userModel.find({
"role": req.query.user_type
}).then(function(users) {
users.forEach(user => {
if(user.doc_id==''){
var user = {
id: user._id,
name: user.fullName,
status: user.status,
role: user.role,
email:user.email,
lastLoginDate: user.lastLoginDate,
lastLoginTime: user.lastLoginTime,
flag:'0'
}
userData.push(user);
}
else{
var usr = {
id: user._id,
name: user.fullName,
picture: `${filelink}/api/usersData/download?document_id=${user.doc_id}`,
status: user.status,
role: user.role,
email:user.email,
lastLoginDate: user.lastLoginDate,
lastLoginTime: user.lastLoginTime,
flag:'1'
}
userData.push(usr);
}
})
res.send({
status: 200,
data: userData
})
})
"use strict";
module.exports = function(sequelize, DataTypes) {
var userMysql = sequelize.define("tce_users", {
user_name: DataTypes.STRING(100),
user_password: DataTypes.STRING,
surname: DataTypes.STRING(100),
user_email: DataTypes.STRING(100),
user_firstName:DataTypes.STRING(100),
user_lastname:DataTypes.STRING(100),
user_birthdate:DataTypes.String(17),
user_birthplace:Datatypes.STRING(100),
user_regnumber:DataTypes.STRING(100),
user_ssn:DataTypes.STRING(100),
user_level:DataType.STRING(100),
user_verifycode:Datatypes.STRING(100)
});
return userMysql;
};
Since, Node JS is single threaded, after insertion into mysql line of code executes before establishment of connection with mysql db. Somehow connecting with mysql require time therefore next block code executes before connection happen.
Firstly, you need to change approach where you need to connect mysql,
Connection string probably should not be in the post api itself,
it's needs to be connect when application starts using some config utility.
Either you can choose promise to resolve the execution of insertion into
mysql or can use async await approach to insert the data after mysql
connection established.

Node Mysql Serialize 'ERR_BUFFER_OUT_OF_BOUNDS'

so when i try to run the project i get the above mentioned error. I am simply creating 2 tables and then running serialize.sync(). I am new to both node, mysql, and serielize so i have absolutely no clue why is this happening. Also if you wanna see eveything here is the github project: https://github.com/EmilBabazade/BooksBLog/tree/migrate_to_mysql
I also tried deleting blog_books_dev with mysql cli and running again, it gives the same error regardless of wether the database exist or not.
Here is what error looks like:
[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
server is running on port 3001
tedious deprecated The default value for `config.options.trustServerCertificate` will change from `true` to `false` in the next major version of `tedious`. Set the value to `true` or `false` explicitly to silence this message. node_modules/sequelize/lib/dialects/mssql/connection-manager.js:63:26
tedious deprecated In the next major version of `tedious`, creating a new `Connection` instance will no longer establish a connection to the server automatically. Please use the new `connect` helper function or call the `.connect` method on the newly created `Connection` object to silence this message. internal/process/task_queues.js:79:11
internal/buffer.js:75
throw new ERR_BUFFER_OUT_OF_BOUNDS();
^
RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to access memory outside buffer bounds
at boundsError (internal/buffer.js:75:11)
at Buffer.readUInt8 (internal/buffer.js:243:5)
at Packet.type (/home/emil/emil/projects/blogBooks/node_modules/tedious/lib/packet.js:143:24)
at IncomingMessageStream.processBufferedData (/home/emil/emil/projects/blogBooks/node_modules/tedious/lib/incoming-message-stream.js:72:26)
at IncomingMessageStream._transform (/home/emil/emil/projects/blogBooks/node_modules/tedious/lib/incoming-message-stream.js:107:10)
at IncomingMessageStream.Transform._read (/home/emil/emil/projects/blogBooks/node_modules/tedious/node_modules/readable-stream/lib/_stream_transform.js:177:10)
at IncomingMessageStream.Transform._write (/home/emil/emil/projects/blogBooks/node_modules/tedious/node_modules/readable-stream/lib/_stream_transform.js:164:83)
at doWrite (/home/emil/emil/projects/blogBooks/node_modules/tedious/node_modules/readable-stream/lib/_stream_writable.js:409:139)
at writeOrBuffer (/home/emil/emil/projects/blogBooks/node_modules/tedious/node_modules/readable-stream/lib/_stream_writable.js:398:5)
at IncomingMessageStream.Writable.write (/home/emil/emil/projects/blogBooks/node_modules/tedious/node_modules/readable-stream/lib/_stream_writable.js:307:11)
at Socket.ondata (_stream_readable.js:708:22)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:273:9)
at Socket.Readable.push (_stream_readable.js:214:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
code: 'ERR_BUFFER_OUT_OF_BOUNDS'
}
[nodemon] app crashed - waiting for file changes before starting...
Here is the code for database:
const Sequelize = require('sequelize')
const User = require('./models/user')
const Blog = require('./models/blog')
const logger = require('../utils/logger')
const dbConfigs = require('./config')
let sequelize
if (process.env.NODE_ENV === 'production') {
sequelize = new Sequelize(dbConfigs.production)
} else if (process.env.NODE_ENV === 'development') {
sequelize = new Sequelize(dbConfigs.development)
} else if (process.env.NODE_ENV === 'test') {
sequelize = new Sequelize(dbConfigs.test)
} else {
logger.error('error when connecting to db, invalid or empty NODE_ENV')
// throw something ..?
}
const userModel = sequelize.define('user', User)
const blogModel = sequelize.define('blog', Blog)
userModel.hasMany(blogModel)
blogModel.belongsTo(userModel)
module.exports = {
sequelize,
User: userModel,
Blog: blogModel,
}
Code for user model:
const Sequelize = require('sequelize')
module.exports = {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
username: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validate: {
len: [5, 20],
},
},
name: Sequelize.STRING,
passwordHash: {
type: Sequelize.STRING,
allowNull: false,
},
isAdmin: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
}
code for blog model:
const Sequelize = require('sequelize')
module.exports = {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
title: {
type: Sequelize.STRING,
AllowNull: false,
validate: {
len: [5, 20],
},
},
content: {
type: Sequelize.STRING,
AllowNull: false,
validate: {
len: [20, 500],
},
},
date: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
},
}
and the options for new Serialize(options) (i deleted password because its my main password for everything irl):
const production = 'link to production db'
const development = {
host: 'localhost',
database: 'blog_books_dev',
username: 'root',
password: '',
dialect: 'mssql',
// open mysql command line and type SHOW GLOBAL VARIABLES LIKE 'PORT';
// to see waht port mysql is running on
port: '3306',
}
const test = {
host: 'localhost',
database: 'blog_books_test',
username: 'root',
password: '',
dialect: 'mssql',
port: '3306',
}
module.exports = { production, development, test }
I wrote mssql instead of mysql:
const development = {
host: 'localhost',
database: 'blog_books_dev',
username: 'root',
password: '',
dialect: 'mssql',
// open mysql command line and type SHOW GLOBAL VARIABLES LIKE 'PORT';
// to see waht port mysql is running on
port: '3306',
}
should be:
const development = {
host: 'localhost',
database: 'blog_books_dev',
username: 'root',
password: '',
dialect: 'mysql', // THIS WAS THE PROBLEM
// open mysql command line and type SHOW GLOBAL VARIABLES LIKE 'PORT';
// to see waht port mysql is running on
port: '3306',
}

How to renew connection of database for iam authentication

Using IAM database authentication the password expires after about 15 minutes. So I ideally have to renew the database connection before the password expires. I set up a timer on the first initialization of the database and query the passed time on each query. How can i refresh the password of the connection before the password expires? Or how can i destroy the old database object and renew the object if necessary?
The error message is: "PAM authentication failed for user iam_user".
code for getting IAM Password:
const pgp = require('pg-promise')();
const AWS = require('aws-sdk');
const ca =
'-----BEGIN CERTIFICATE-----\nMIID9DCCAtyg...
...wZfTUU=\n-----END CERTIFICATE-----\n';
const signer = new AWS.RDS.Signer({
region: process.env.REGION,
username: process.env.DATABASE_USER,
hostname: process.env.DATABASE_HOST,
port: parseInt(`${process.env.DATABASE_PORT}`, 10),
});
module.exports = pgp({
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USER,
ssl: { ca },
dialectOptions: { ssl: { require: true } },
password: signer.getAuthToken(),
});
injecting db object to graphql:
const db = require('../db/init');
server.use(
mount(
'/graphql',
graphqlHTTP( () => ({
schema: schema,
context: { startTime: Date.now(), db },
graphiql: true
})),
),
);
Using the database in the resolvers.
I could query the time of the creation of the database connection. Is there a possibility to renew the password if necessary? Or what is the best way to destroy the old database object and create a new database object?
const resolvers = {
Query: {
Post: (root, args, {db}) => {
console.log(args.id);
console.log(db.$config.options)
const postQuery = new PQ({
text:
'SELECT post_id as id FROM tbl_post where post_id = $1',
values: [parseInt(args.id, 10)],
});
return db.one(postQuery).catch((err) => console.log(err));
}
}
As suggested by vitaly-t i used a password function. To avoid adding latency this functions renews the password only every 15 minutes. If the pool gets continuously used in intervals lower than 10 seconds, than the connection stays open without calling the password function at all. According to my tests there are no new connections to the database opened at all.
const ca = '-----BEGIN CERTIFICATE-----\9DC...-----END CERTIFICATE-----\n';
const signer = new AWS.RDS.Signer({
region: process.env.REGION,
username: process.env.DATABASE_USER,
hostname: process.env.DATABASE_HOST,
port: parseInt(`${process.env.DATABASE_PORT}`, 10),
});
const SIGNER = { time: 0, password: undefined};
function getSignedPassword() {
const time = Date.now();
if (time - SIGNER.time > 900000) {
SIGNER.time = new Date().getTime();
SIGNER.password = signer.getAuthToken();
return SIGNER.password;
}
return SIGNER.password;
}
module.exports = pgp({
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USER,
ssl: { ca },
password: getSignedPassword,
});

Connect Sequelize/Node to XAMPP Mysql

I've a working script to connect and work with Sequelize on Node.js
But now i'm trying to connect this to my MySQL database on XAMPP
MySQL Port on XAMPP: 3306
When i run node.js after i have configured the app.listen and the config of sequealize i get the following error
ERROR: listen EADDRINUSE :::3306
I've looked for but i didn't find much information about that, i don't know what i'm doing bad.
Thanks you for every answer!
app.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const { sequelize } = require('./models')
const config = require('./config/config')
const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())
require('./routes')(app)
sequelize.sync()
.then(() => {
app.listen(config.db.options.port || 3306) // 8081 original
console.log(`Server iniciado en puerto: ${config.db.options.port}`)
})
config.js
module.exports = {
db: {
database: process.env.DB_NAME || 'intraenvios',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASS || '',
options: {
dialect: process.env.DIALECT || 'mysql', // sqlite original
host: process.env.HOST || 'localhost',
storage: './intraenvios.sqlite',
port: process.env.PORT || 3306 // 8081 original
}
}
}
EDIT:
For to connect by xampp simply, i made this:
const sequelize = new Sequelize('test', 'root', '', {
host: "127.0.0.1",
dialect : 'mysql',
operatorsAliases: false
});
sequelize.authenticate().then(function(){
console.log("sucess");
}).catch(function(error){
console.log("error: "+error);
});
Obs: operatorsAliases: false - To fix deprecated message of sequelize
Good Fun :)

bug with angular2-meteor app :failed connection to mysql via meteor

i'm trying to connect to mysql database with meteor using nodets:mysql and i'm facing this error :
Unhandled rejection Error: No infromation can be fetched by your database, please check your permissions
this is my part of code :
Meteor.startup(function() {
//Start of changes
var connectionSettings = {
host: '127.0.0.1',
user: 'root',
password: '',
database: 'test'
};
var db = Mysql.connect(connectionSettings);
})
i need to add the port of mysql
Meteor.startup(function() {
//Start of changes
var connectionSettings = {
host: '127.0.0.1',
port : (mysqlport),
user: 'root',
password: '',
database: 'test'
};
var db = Mysql.connect(connectionSettings);
})