Sequelize connection with Nodejs - javascript

I am facing issue on connection of SEQUELIZE(mysql) with NodeJs. Though connection is established but models are not properly configured. I have use this approach --
./config/sequelize-conn.js
'use strict';
var sequelize = function (config, Sequelize) {
var sql = new Sequelize(config.mysql.db, config.mysql.user, config.mysql.pass, {
host: config.mysql.host,
dialect: 'mysql', //|'sqlite'|'postgres'|'mssql'
pool: {
max: 5,
min: 0,
idle: 10000
},
//logging: true,
underscored: true
});
sql
.sync({force: true})
//.authenticate()
.then(function () {
console.log('Connection has been established successfully with mysql.');
}, function (error) {
console.log('Connection with mysql failed.', error);
});
return sql;
};
module.exports = sequelize;
//server.js
var sequelize = require('sequelize');
var sqlConnection = require('./config/sequelize-conn')(config, sequelize);
I wish to directly use model this way ..
models/HotelGroup.js
var Sequelize = require('sequelize');
var sequelize = require('../../config/sequelize-conn');
var HotelGroup = Sequelize.define('hotel_chains', {
id: {
type: Sequelize.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
hotel_name: {
type: Sequelize.STRING,
allowNull: false
},
hotel_code: {
type: Sequelize.STRING,
allowNull: false
},
status: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: '1'
}
}, {
tableName: 'hotel_chains',
timestamps: false,
paranoid: true // Model tableName will be the same as the model name
});
module.exports = HotelGroup;
Its giving me error that sequelize.define is not a function.
Though connection is establishing but when I try to access any model in service file using require. It breaks with this error message. Where I am doing wrong.

I think you need to use the instance of sequelize, not the class. So sequelize.define not Sequelize.define.
Also, you need to instantiate it properly: var sequelize = new Sequelize(...)

Related

Sequelize foreing key is not creating

I try to create a relation between 2 tables with Sequelize in NodeJS for MariaDB.
I have 2 tables order and local, the table order needs one of the information of the table local.
The order table contains information about an order (id: 1, type: Jacket, color: blue, tracking_number: TR123)
The table local contains information about the place where the order is stored (address: 20 rue madeline, city: Paris)
I tried to link the two tables but it does not work, the foreing key is not created
models/order.js
module.exports = (sequelize, DataTypes) => {
const Order = sequelize.define('order', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
trackingNumber: {
type: DataTypes.STRING,
allowNull: false
},
type: {
type: DataTypes.STRING(50),
allowNull: false
},
color: {
type: DataTypes.STRING(50),
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
tel: {
type: DataTypes.STRING(10),
allowNull: false
}
}, {
timestamps: true,
createdAt: true,
updatedAt: 'updateTimestamp'
})
Order.associate = function (models) {
Order.hasOne(models.local);
}
return Order;
}
models/local.js
module.exports = (sequelize, DataTypes) => {
const Local = sequelize.define('local', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
adress: {
type: DataTypes.STRING,
allowNull: false
},
informations_about: {
type: DataTypes.STRING,
allowNull: false
},
contact: {
type: DataTypes.STRING,
allowNull: false
},
city: {
type: DataTypes.STRING,
allowNull: false
},
zip: {
type: DataTypes.STRING(5),
allowNull: false
},
}, {
timestamps: true,
createdAt: true,
updatedAt: 'updateTimestamp'
})
return Local;
}
app.js
// Imports
const express = require('express')
const morgan = require('morgan')
const db = require('./database')
const sequelize = require('./database').sequelize;
var apiRouter = require('./apiRouter.js').router;
var helmet = require('helmet');
const app = express()
const port = process.env.PORT || 3000;
// Init server
app.use(morgan('combined'))
// Parser config
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// Security API
app.use(helmet());
app.disable('x-powered-by');
app.use(({ res }) => {
res.status(404).json({ message: "404 Not Found" })
})
db.sequelize.authenticate()
.then(_ => console.log("La connexion à bien été établie."))
.catch(error => console.log(`error ${error}`))
db.sequelize.sync({ force: true })
.then(_ => {
console.log("Base de donnée synchronisée.")
app.use('/api/', apiRouter);
})
app.listen(port, () => {
console.log("Server is up and listening in " + port)
})
database.js
const fs = require('fs')
const path = require('path')
const { Sequelize } = require('sequelize')
const db = {}
const models = path.join(__dirname, 'models') // correct it to path where your model files are
const sequelize = new Sequelize(
'',
'',
'',
{
host: 'localhost',
dialect: 'mariadb',
dialectOptions: {
useUTC: false, // for reading from database
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
logging: false
}
)
var basename = path.basename(module.filename)
fs
.readdirSync(models)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
})
.forEach(function (file) {
const model = require(path.join(__dirname + '/models', file))(sequelize, Sequelize.DataTypes)
db[model.name] = model
})
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})
db.Sequelize = Sequelize // for accessing static props and functions like Op.or
db.sequelize = sequelize // for accessing connection props and functions like 'query' or 'transaction'
module.exports = db
Despite the associate function in the model/order.js it does not work, I have no key in my order table
You have to manually call all associate functions in order to register associations between models and only after all models are already registered in the Sequelize instance. You can look at my other answer to see how you can do it.
And please show the content of database module and then I probably correct my answer or append more useful tips.

Sequelize failing to create a table with the error "Executing (default): SELECT 1+1 AS result"

Thank you for taking the time to help out. When running my server I am getting a message "Executing (default): SELECT 1+1 AS result". My tables are not being created. How do I fix this error? I am using the technologies MySQL, Sequelize, JavaScript, Express, and Node.
Connection.js (I have checked the .env and the information is accurate)
const Sequelize = require('sequelize');
require('dotenv').config();
const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PW, {
host: 'localhost',
dialect: 'mysql',
port: 3306
});
module.exports = sequelize;
Schema.sql
DROP DATABASE IF EXISTS events_db;
CREATE DATABASE events_db;
Customer model
const { DataTypes, Model } = require('sequelize');
const sequelize = require('../config/connection');
class Customer extends Model {}
Customer.init(
{
uuid: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV1,
primaryKey: true,
allowNull: false,
unique: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true,
}
},
phone: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true,
is: /^[\+]?[(]?\d{3}[)]?[-\s\.]?\d{3}[-\s\.]?\d{4,6}$/im
}
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
address: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true
}
}
},
{
sequelize,
freezeTableName: true,
underscored: true,
modelName: 'customer'
}
);
module.exports = Customer;
Model index.js
const Customer = require('./Customer');
const Event = require('./Event');
const EventType = require('./EventType');
const Reservation = require('./Reservation');
Customer.hasMany(Reservation, {foreignKey: { allowNull: false }});
Event.hasMany(Reservation, {foreignKey: { allowNull: false }});
Event.hasOne(EventType, {foreignKey: { allowNull: false }});
Event.hasOne(Customer, {foreignKey: { allowNull: false }});
module.exports = { Customer, Event, EventType, Reservation };
Server.js
const express = require('express');
const sequelize = require('./config/connection');
const app = express();
const PORT = process.env.PORT || 3001;
const routes = require('./routes');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use(routes);
sequelize.sync({ force: false }).then(() => {
app.listen(PORT, () => {
console.log(`App is listening on port ${PORT}`);
});
});
Imported models into server.js file. Did not need to call the variable. This allowed for sequelize to "see" my models. When implementing a controller or GraphQL, this import can be removed.

TypeError: Cannot read property 'findAll' of undefined (mariaDB, ExpressJs)

TypeError: Cannot read property 'findAll' of undefined
findAll function makes error, but Connection was successful.
And database is also created under the name managers.
app.js
models
index.js
maria
manager.model.js
bin
www.js
models/index.js
const { Sequelize } = require('sequelize');
const manager = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxx',
password: 'xxx',
database: 'test',
timezone: 'Asia/Seoul'
});
require('./maria/manager.model')(manager);
module.exports=manager;
models/maria/manager.model.js
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
sequelize.define('manager', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
allowNull: false,
type: DataTypes.STRING,
}
}, {timestamps: true }).sync({force:false});
};
app.js
const express = require('express');
const app = express();
const db = require('./models');
console.log(`Checking database connection...`);
// It works!
db.authenticate().then(()=>{
console.log('Database connection OK!');
});
// It makes error!
const find_test = db.manager.findAll();
console.log(find_test);
First of all what is containing your manager variable ?
your manager variable is containing the connection sequelize. Your objectif is to request your table manager but you can't to this with the variable. Because he doesn't contain table specification but database connection.
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
return sequelize.define('manager', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
allowNull: false,
type: DataTypes.STRING,
}
}, {timestamps: true });
};
In this file, you need to return the definition of your table.
const { Sequelize } = require('sequelize');
const manager = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxx',
password: 'xxx',
database: 'test',
timezone: 'Asia/Seoul'
});
const myTable = require('./maria/manager.model')(manager);
module.exports= {
manager, myTable
};
and in this file, you need to store the return value in a variable.and export it.
const express = require('express');
const app = express();
const { manager, myTable }= require('./models');
console.log(`Checking database connection...`);
// It works!
manager.authenticate().then(()=>{
console.log('Database connection OK!');
});
const find_test = myTable.findAll();
console.log(find_test);
Finaly in the next file, import the new exported variables ! and Enjoy !
app.js
sequelize
models
manager.model.js
index.js
app.js
const maria = require('./sequelize');
const { models } = require('./sequelize');
console.log(`Checking database connection...`);
maria.authenticate()
.then(()=>{
console.log('Database connection OK!');
});
const test = models.manager.findOne()
sequelize/index.js
const { Sequelize } = require('sequelize');
const maria = new Sequelize({
dialect: 'mariadb',
host: '127.0.0.1',
port: '13306',
username: 'xxxx',
password: 'xxxx',
database: 'test',
timezone: 'Asia/Seoul'
});
require('./models/manager.model')(maria)
module.exports=maria;

how to fix getting undefined for model classes using sequelize?

I am learning to use sequelize with my Next.js app.I set up the sequelize, used the cli to generate migrations, created the model (user) , and when i try to test it, going to the http://localhost:3000/api/app . i get an error -> Cannot read property 'findAll' of undefined.
my model class is coming up as undefined. anyone has any idea?
*director structure
MyApp
...
> database
- db.js
> migrations
> models
-user.js
> node_modules
> pages
> api
- app.js
db.js
const Sequelize = require('sequelize');
const db = new Sequelize('mydb', 'root', 'pass', {
host: "localhost",
port: 3306,
dialect: 'mysql',
operatorsAliases:false,
logging: function () {},
pool: {
max: 5,
min: 0,
idle: 10000
},
dialectOptions: {
socketPath: "/var/run/mysqld/mysqld.sock"
},
define: {
paranoid: true
}
});
db.authenticate().then(() => {
console.log('connection error');
}).catch(err => {
console.log('Connection successful');
});
module.exports = db;
model/User.js
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define("User", {
id : {
type: DataTypes.INTEGER(11),
allowNull: false,
autoIncrement:true,
primaryKey:true
},
firstName : {
type: DataTypes.STRING(50),
allowNull: false
}
lastName : {
type: DataTypes.STRING(50),
allowNull: false
},
created: {
type: 'TIMESTAMP',
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
allowNull: false
},
updated:{
type: 'TIMESTAMP',
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
allowNull: false
}
});
return user;
};
pages/api/app.js
const models = require('../../models')
export default (req, res) => {
models.user.findAll(); //error => Cannot read property 'findAll' of undefined
};
You define uppercase User in the User.js file, so you have to use it uppercase:
const models = require('../../models');
export default async (req, res) => {
const users = await models.User.findAll();
console.log(users);
};

Getting validator error in Sequelize.js

Im trying to validate a username and password to not be null when there is a post request made so that there are no empy rows, but I keep getting
Express server listening on port 5000
/Users/ra/Desktop/Jos/node_modules/sequelize/lib/dao-validator.js:216
throw new Error("Invalid validator function: " + validatorType)
^
Error: Invalid validator function: allowNull
heres the the employer model
'use strict';
var Sequelize = require('sequelize');
module.exports = function (sequelize) {
var Employer = sequelize.define("employer", {
username: { type: Sequelize.STRING, validate: { allowNull: false } },
password: { type: Sequelize.STRING, validate: { allowNull: false } }
});
return {
Employer: Employer
};
};
allowNull must be in field options, not in validator:
var Sequelize = require('sequelize');
'use strict';
var Sequelize = require('sequelize');
module.exports = function (sequelize) {
var Employer = sequelize.define("employer", {
username: { type: Sequelize.STRING, allowNull: false },
password: { type: Sequelize.STRING, allowNull: false }
});
return {
Employer: Employer
};
};
See doc here and comment of source code here
Before Sequelize 2.0 you could use notNull validator, but it was removed in 2.0 version (see 2.0 changes here)

Categories