sequelize.query() is not a FUNCTION - node.js

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));

Related

Sequlize .authenticate? err

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')

Nodejs MSSQL how to pool multiple databases simultaneously

I am building a massive intranet using NodeJS, converting from ASP.Net C#. I keep running into database errors about cannot use the connection while it is closing or connection must be opened etc. I am attempting to convert over to connection pooling but am running into issues with it since I am connecting with (currently) 6 different databases, and being new to Node MSSQL I am kind of at a loss for how to proceed.
Originally I was making a call to "runqueries()" passing in the config data, and from there opening a connection to the desired database. The connection details were stored in a JSON object in the database.js file. I am now trying to create the pool in the database.js file and return that as an object to connect.
//database.js
const sql = require('mssql');
// const Config = {
// MCAIntranet: {
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'MCAIntranet',
// options: { enableArithAbort: true }
// },
// DEV_Intranet: {
// server: 'mcasql',
// user: 'username',
// password: 'password',
// database: 'DEV_Intranet_Test',
// options: { enableArithAbort: true }
// },
// CMR: {
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'Corporate_Morning_Reports',
// options: { enableArithAbort: true }
// },
// Lansa: {
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'LANSA',
// options: { enableArithAbort: true }
// },
// Roles: {
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'dotNetRolesDB_New',
// options: { enableArithAbort: true }
// },
// PreAuth:{
// user: 'username',
// password: 'password',
// server: 'mcasql',
// database: 'PreAuth',
// options: { enableArithAbort: true }
// }
// }
const CORPIntranet = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'CORPIntranet',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const DEV_Intranet = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'CORPIntranet_Test',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const CMR = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'Corporate_Morning_Reports',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const Lansa = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'LANSA',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const Roles = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'dotNetRolesDB_New',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const PreAuth = () => {
new sql.ConnectionPool({
user: 'username',
password: 'password',
server: 'dbserver',
database: 'PreAuth',
options: { enableArithAbort: true }
})
.connect().then(pool => pool)
};
const Config = {
CORPIntranet: CORPIntranet(),
DEV_Intranet: DEV_Intranet(),
CMR: CMR(),
Lansa: Lansa(),
Roles: Roles(),
PreAuth: PreAuth()
}
module.exports = Config;
I am calling this using the code await dataQuery.runQuery(query, config.PreAuth);
and the runquery() code is
//dataQueries.js
let sql = require('mssql');
const runQuery = async (query, database) => {
try {
// await sql.connect(database);
// let request = new sql.Request();
let recordset = await database.query(query);
return recordset;
} catch (ex) {
console.log(ex);
{ error: "dataQueries.js 17" + ex.Message };
return "False";
}
finally{
sql.close();
}
}
I know that I don't need the "sql.close()" at the end but I am in the process of conversion. I am now getting a typeError: database.query is not a function.
If you could point out where my fault lies in this, and better yet link a good tutorial that assumes neophyte status of the reader, that would be excellent.
Thanks in advance.
EDIT
In my runQuery() function I changed the code to
let pool=await database();
let recordset = await pool.query(query);
which now allows the query to run. But is this the correct method and will it prevent errors on multiple database connections?
I solved this problem in the simplest fashion possible. I switched from using the mssql module to sequelize.js which gives a level of abstraction from the database access and connectivity, and simplifies access to multiple databases along with database types (MSSQL, Postgres, MongoDB etc)

How to fix the model.create() is not a function error in Sequelize ORM

I am new with nodejs so please go easy on me.
I am setting up a nodejs server to connect to a mysql database using Sequelize.
I currently have an error "model.create is not a function" which I cannot find any related fixes on google.
Please help me out.
Thanks in advance
This is my model.js file
const sequelize = require('sequelize');
module.exports = (sequelize, DataTypes) => {
const Data = sequelize.define('Data',
{
oxyVal: {
type: DataTypes.DOUBLE,
allowNull: false
},
mqState: {
type: DataTypes.BOOLEAN,
allowNull: false
},
date: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
}
});
return Data;
}
This is my index.js file
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const Sequelize = require('sequelize');
const Data = require('../models/data');
const app = express();
const port = 5500;
// I will now connect to my database
mySequelize = new Sequelize('Fast', 'root', '[password]', {
host: '127.0.0.1',
dialect: 'mysql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
// Test database connection here
mySequelize.authenticate().then(() => {
console.log('Database connected successfully');
}).catch((err) => {
console.error('Failed to connect to database \n ' + err);
})
app.use(morgan('dev'));
//app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser());
app.get('/');
app.post('/', (req, res, next) => {
const myData = Data.create({
oxyVal: req.body.oxyVal,
mqState: req.body.mqState,
time: req.body.time,
time: req.body.id
}).then(JSON.parse(myData)).myData.save().then((result) => {
console.log(result);
}).catch((err) => {
console.log(err);
});;
res.send('Record successfully saved');
console.log(myData);
});
app.listen(port)
console.log("Server satrted on " + port + " .....");
I was able to get your code working by doing the following 3 things:
1) rename model.js to data.js and putting it in the same directory as index.js.
2) change this:
const Data = require('../models/data');
To this:
const db = require('./data');
3) create a database 'fast', a user 'toor', with password 'password', and granted the 'toor' user full access to the 'fast' database. The connect line then ends up looking like this:
mySequelize = new Sequelize('fast', 'toor', 'password', {
Please take a look the sequelize CLI, it can help lay out your directory structure in a convenient way: http://docs.sequelizejs.com/manual/tutorial/migrations.html#the-cli

sequelize datatypes.NOW function does not generate timestamp

My code is as shown below:
let time = db.Sequelize.DataTypes.NOW;
console.log('generated time is' + time);
db.js
const Sequelize = require('sequelize');
require('dotenv').config();
const db = {};
var sequelize = new Sequelize({
host: process.env.DB_HOST,
database: process.env.DB_NAME,
username: process.env.DB_USER_NAME,
password: process.env.DB_PASSWORD,
dialect: process.env.DB_TYPE,
port: process.env.DB_PORT,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
operatorsAliases: false
});
sequelize
.authenticate()
.then(() => {
console.log('connected to database successfully')
})
sequelize.sync({
force: false
})
db.Sequelize = Sequelize;
db.sequelize = sequelize;
The output that I get is
generated time is function NOW() {
if (!(this instanceof NOW)) return new NOW();
}
How can I generate timestamp with value ?
That's absolutely the right way how it should work. Why do you think, it should return a timestamp? It should not. If you'd like to get a timestamp, just run:
new Date().getTime()
In Migration, you can use literal. This will help you, I also face such problem. This works:
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')

Am I doing connection pooling correctly? Using node-postgres library

I am reading the documentation and trying to figure out connection pooling.
The documentation says that the pool should be long lived, so I have created a config/db.js file where I create pool and export it:
/* src/config/db.js */
const pg = require('pg');
const dbConfig = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_DATABASE,
max: 25,
idleTimeoutMillis: 5000
};
const pool = new pg.Pool(dbConfig);
module.exports = {
pool
};
I have a bunch of routes and controllers. For example, I have /markers endpoint which has a few methods in the controller. In the controller file, I am importing pool from the config/db.js and using it. Is that OK?
const pool = require('../config/db').pool;
const create = function (req, res, next) {
const data = {
created_by: req.body.createdBy,
title: req.body.title,
description: req.body.description,
lat: req.body.lat,
lng: req.body.lng
};
pool.connect((err, client, done) => {
if (err) {
done();
// console.log(err);
return res.status(500).json({ success: false, data: err });
}
client.query(
'INSERT INTO markers(created_by, title, description, lat, lng, geography)\
values($1, $2, $3, $4::decimal, $5::decimal, ST_SetSRID(ST_MakePoint($5::decimal, $4::decimal), $6))',
[
data.created_by,
data.title,
data.description,
data.lat,
data.lng,
4326
],
function(err, res) {
done();
if (err) {
// console.log(err);
}
}
);
return res.status(200).json({ success: true });
});
};
Also, how do I check that the insert was successful so that I don't just return a 200 success if there's no error without knowing if the insert was successful?
that's correct.
as for checking error, you can see right there in the callback where you check if (err), in case no err is return, that mean the insertion is success.

Resources