i use sequelize in my node.js project, and i dont know how to export and use table model in another file.
I save table models in folder for example Profile.js
module.exports = (sequielize, DataTypes) => sequielize.define('Profile', {
ID: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false
},
Login: {
type: DataTypes.STRING(24),
allowNull: false
},
SocialClub: {
type: DataTypes.STRING(128),
allowNull: false
},
Email: {
type: DataTypes.STRING(64),
allowNull: false
},
RegIP: {
type: DataTypes.STRING(17),
allowNull: false
},
LastIP:
{
type: DataTypes.STRING(17),
allowNull: false
},
RegDate: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false
},
LastDate: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
allowNull: false
}
});
And I have such database module database.js:
const Sequelize = require('sequelize');
const fs = require('fs')
const path = require('path')
const config = require('../configs/server_conf');
db = {};
const sequelize = new Sequelize(
config.db_settings.database,
config.db_settings.user,
config.db_settings.password,
config.db_settings.options);
db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.checkConnection = async function() {
sequelize.authenticate().then(() => {
console.log('Подключение к базе данных прошло успешно!');
//import db models
fs.readdirSync(path.join(__dirname, '..', 'models')).forEach(file => {
var model = sequelize.import(path.join(__dirname, '..', 'models', file));
db[model.name] = model;
});
sequelize.sync({
force: true
}).then(() => {
console.log('synchroniseModels: Все таблицы были созданы!');
}).catch(err => console.log(err));
mp.events.call("initServerFiles");
}).catch(err => {
console.error('Невозможно подключиться к базе данных:', err);
});
}
module.exports = db;
And i have such an index.js file where i'm exporting checkConnection function:
"use strict"
const fs = require('fs');
const path = require('path');
const { checkConnection } = require('./modules/database.js');
var Events = [];
mp.events.add(
{
"initServerFiles" : () =>
{
fs.readdirSync(path.resolve(__dirname, 'events')).forEach(function(i) {
Events = Events.concat(require('./events/' + i));
});
Events.forEach(function(i) {
mp.events.add(i);
console.log(i);
});
mp.events.call('initServer');
console.log("Загрузка всех файлов прошла успешно!");
}
});
checkConnection();
So in a nutshell, how i can export my Profile table and use it, for example:
Profile.create({
Login: "0xWraith",
SocialClub: "0xWraith",
Email: "mail#gmail.com",
RegIP: "127.0.0.1",
LastIP: "127.0.0.1",
LastDate: "07.04.2020"
}).then(res => {
console.log(res);
}).catch(err=>console.log(err));
So you already have all registered models in the database.js module. Just import the whole database.js like this:
const db = require('./modules/database.js');
...
db.Profile.create({
Login: "0xWraith",
SocialClub: "0xWraith",
Email: "mail#gmail.com",
RegIP: "127.0.0.1",
LastIP: "127.0.0.1",
LastDate: "07.04.2020"
}).then(res => {
console.log(res);
}).catch(err=>console.log(err));
Related
These are my models:
Staff
const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize')
const Staff = sequelize.define('Staff', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
SSN: {
type: DataTypes.INTEGER,
},
email:{
type: DataTypes.STRING,
}
}, {
timestamps: true
});
Staff.associate = function (models) {
Staff.belongsToMany(models.Technology, {through: models.StaffTechnology});
};
module.exports = Staff;
Technology:
const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize')
const Technology = sequelize.define('Technology', {
name: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.STRING,
}
}, {
timestamps: true
});
Technology.associate = function (models) {
Technology.belongsToMany(models.Staff, { through: models.StaffTechnology});
};
module.exports = Technology;
This will be the join table:
const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize')
const Staff = require('../../database/models/staff.model');
const Technology = require('../../database/models/technology.model');
const StaffTechnology = sequelize.define('StaffTechnology', {
experience: {
type: DataTypes.INTEGER,
},
StaffID: {
type: DataTypes.INTEGER,
references: {
model: Staff,
key: 'id'
}
},
TechnologyID: {
type: DataTypes.INTEGER,
references: {
model: Technology,
key: 'id'
}
},
}, {
timestamps: true
});
StaffTechnology.associate = function (models) {
//StaffTechnology.hasMany(models.Staff, { foreignKey: 'StaffID' });
//StaffTechnology.hasMany(models.Technology, { foreignKey: 'TechnologyID' });
};
module.exports = StaffTechnology
Right now I cant do a Staff.findAll({include:Technology}), since it give me an error saying that Staff and Technology are not associated, but I saw Sequelize documentation, and I saw a very similar example working.
What I want is the posibility to return All Staffs with their technologies, Staff can have many technologies, and Technologies can belong to Many Staffs, but in reality they are connected through StaffTechnology join table.
You need to declare the associations inside of your index.js (or where you initialize your DB). You can either do it manually by declaring the associations directly by requiring the models and doing
Model1.association(Model2, {
through: "JoinTable"
}
Model2.association(Model1, {
through: "JoinTable"
}
Or do it programmatically (If you are already using that approach to initialize your DB):
'use strict'
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const config = {
"username": "root",
"password": "YOUR ROOT PASSWORD HERE",
"database": "YOUR DATABASE NAME HERE",
"host": "127.0.0.1",
"dialect": "mysql"
}
const db = {}
let sequelize = new Sequelize(config.database, config.username, config.password, config);
fs.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0)
&& (file !== basename)
&& (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
^ This code does both the initialization and the associations in one. You need to make sure that your model files and the initialization file are in the same folder.
This is my Cliente.js that its a model
const Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
const cliente = sequelize.define('cliente', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
nombre: {
type: DataTypes.STRING(20),
allowNull: true
}
}, {
sequelize,
tableName: 'cliente',
timestamps: false,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "id" },
]
},
]
});
return cliente;
};
and that is my app.js
var express = require('express');
const Sequelize = require('sequelize');
const Cliente = require("./Modelos/cliente")
var app = express();
const db = require("./database/db")
db.sequelize.authenticate().then(() => {
console.log('Connection has been established successfully.');
console.log(Cliente)
}).catch(err => {
console.error('Unable to connect to the database:', err);
});
The line "console.log(Cliente) returns me "[Function]" and not the model.
how can i get the model and not the function?
So try changing this line
module.exports = function(sequelize, DataTypes) {
To
exports.sequ = function(sequelize, DataTypes) {
Then
Change
const Cliente = require("./Modelos/cliente");
And this line to
console.log(Cliente.sequ)
I would suggest rereading how to work with sequelize and rewrite the codebase.
Cliente.js - exports the function with has 2 parameters.
console.log(Cliente) - doesn't pass any parameters. Thus how the magic should happen?
Cliente.js - const Sequelize = require('sequelize') is not used.
The models must be defined on the sequelize instance which you are using also connect to DB.
//Cliente.js
const DataTypes = require("sequelize");
const cliente = sequelize => {
const res = sequelize.define('cliente', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
nombre: {
type: DataTypes.STRING(20),
allowNull: true
}
}, {
sequelize,
tableName: 'cliente',
timestamps: false,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "id" },
]
},
]
});
return res;
};
module.exports = cliente
and
// index.js
const Sequelize = require('sequelize')
const sequelize = new Sequelize('postgres://<username>:<password>#<host>:<port>/<db_name>')
;(async () => {
await sequelize.authenticate()
const Cliente = require("./cliente")
const cliente = Cliente(sequelize)
console.log(cliente)
})()
I'm trying to build a relation between the users and his favorite cryptocurrency.
Meaning, multiple Users can have the same crypto as their favorites.
Coin.js
module.exports = (sequelize, DataTypes) => {
const Coin = sequelize.define('Coin', {
cryptoName: DataTypes.STRING,
})
Coin.associate = function(models) {
Coin.belongsToMany(models.CoinsUserRelations, {foreignKey: 'CoinID', through: 'CoinsUserRelations'})
}
return Coin
}
User.js
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: {
type: DataTypes.STRING,
unique: true
},
password: DataTypes.STRING
}, {
hooks: {
beforeSave: hashPassword
}
})
User.associate = function(models) {
User.belongsToMany(models.CoinsUserRelations, {foreignKey: 'UserID', through: 'CoinsUserRelations'})
}
return User
}
These are my 2 tables at the moment and now I'm trying to build a relation between them. and I keep receiving this error on my console which I do not understand why.
I've edited multiple time to resolve the issue, This was the result with the help of Anatoly
CoinsUserRelations.js
module.exports = (sequelize, DataTypes) => {
const CoinsUsersRelations = sequelize.define('CoinsUsersRelations', {
UserID: {
type: DataTypes.INTEGER,
},
CoinID: {
type: DataTypes.INTEGER,
}
})
return CoinsUsersRelations
}
I'm really unsure on why I get this error if I'm actually defining the model before creating the relations..
Index.js
const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}
const sequelize = new Sequelize(
config.db.database,
config.db.user,
config.db.password,
config.db.options
)
fs
.readdirSync(__dirname)
.filter((file) =>
file !== 'index.js'
)
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file))
db[model.name] = model
})
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
Edit part for a bug called SequelizeEagerLoadingError
module.exports = {
async getUserFavoriteCrypto (req, res) {
try {
const coins = await db.Users.findOne({
where: {
UserID : req.query.userId
},
attributes: ['UserID'],
include: [{
model: db.Coins,
required: false
}]
})
console.log(coins)
res.send({
coins: coins
})
} catch (err) {
res.status(400).send({
error: err
})
}
}
}
You should register all models and only after that all their associations in one place. See my answer on a similar problem
I try to create a new researcher but I just go into catch, and I do not get any errors. I am new using sequelize, I need a lot of help for this problem, my complete code in git: https://github.com/chanudinho/RevYou-BackEnd.
I can't explain it better, please if you need to download the project and test it. Sorry for my english =x
researcherController.js
const Researcher = require('../../sequelize/models/researcher');
const createResearcher= async (req, res) => {
try{
Researcher.create({name: 'name', email: 'email', password: 'password'});
return res.status(201).send('sucesso');
}catch (err){
return res.status(500).send('error');
}
}
models/researcher.js
module.exports = (sequelize, DataTypes) => {
const Researcher = sequelize.define('Researcher', {
name: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING
});
return Researcher;
};
migrations/20190114200431-create-researcher
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Researcher', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
allowNull: false,
type: Sequelize.STRING
},
email: {
allowNull: false,
type: Sequelize.STRING
},
password:{
allowNull: false,
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Researcher');
}
};
models/index.js
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const config = require('../../config/database.js');
const db = {};
const sequelize = new Sequelize(config);
fs
.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== path.basename(__filename)) && (file.slice(-3) === '.js'))
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
The problem is that you are importing the model file and this is not right, your index.js within model maps all model files by adding the sequelize instance and the datatypes. You should always import the index.
If you import the model index and give a console.log() in it will see that you have the object of your model and the instance of the sequelize.
const db = require('../../sequelize/models/index');
console.log(db)
Inside the exit will have something like this: Example:
Researcher: Researcher,
sequelize:
Sequelize { ....
To access your model you can do the following. By using destructuring assignment, you extract the model from within the index.
Result
const { Researcher } = require('../../sequelize/models/index')
const createResearcher= async (req, res) => {
try{
await Researcher.create({name: 'name', email: 'email', password: 'password'});
return res.status(201).send('sucesso')
}catch (err){
return res.status(500).send('error');
}
}
Whenever you create a new file inside the model folder, it will be mapped by index.js and added inside the matrix and using destructuring you can access or use the matrix key itself.
const db = require('../../sequelize/models/index')
const createResearcher= async (req, res) => {
try{
await db.Researcher.create({name: 'name', email: 'email', password: 'password'});
return res.status(201).send('sucesso')
}catch (err){
return res.status(500).send('error');
}
}
I have a problem with my code when using sequelize auto.
the problem is how to connect sequelize model to database setting on DB.js, so that we can using findall function or any else
Model :
/* jshint indent: 2 */
const db = require('../../db/database')
const sequelize = db.sequelize
module.exports = function(sequelize, DataTypes) {
cust: sequelize.define('ms_customer', {
id: {
type: DataTypes.CHAR(10),
allowNull: false,
primaryKey: true
},
gender_id: {
type: DataTypes.INTEGER(1),
allowNull: true
},
status: {
type: DataTypes.CHAR(1),
allowNull: true
}
}, {
tableName: 'ms_customer'
});
};
DB.js connection :
const Sequelize = require('sequelize')
const sqlz = new Sequelize('db', 'user', 'pass', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 10,
idle: 10000
}
})
sqlz
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
module.exports = {
sqlz: sqlz,
Sequelize: Sequelize
}
Query :
const customerModel = require('../../db/model/ms_customer')
const cust = customerModel.cust
module.exports = {
modelGetCustomerById : (param,req,res) => {
cust.findAll({
where: {
id: {
param
}
}
}).then(customer => {
// console.log(customer)
res.json(customer)
})
}
}
Controller :
const customer = require('../../db/query/customer')
const sequelize = require('sequelize')
module.exports = {
getCustomerById: async(req,res) => {
var customerId = req.params.id
let getCustomerId = await customer.modelGetCustomerById(customerId)
// console.log(getCustomerId)
if(!getCustomerId){
return res.status(500).json({status: "Failed", message:"User not found"});
}
return res.status(200).json({status: "Success", message:getCustomerId});
}
}
why i always got error
Cannot read property 'findAll' of undefined
please help..
I've running code without error on my project that remodel by sequelize-auto and connect by sequelize. Check it out :
on models/index.js: ( for connection to db )
'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.json')[env];
const db = {};
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);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
On models/m_bank.js code :
module.exports = function(sequelize, DataTypes) {
return sequelize.define('m_bank', {
bank: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: '',
primaryKey: true
},
bank_name: {
type: DataTypes.STRING,
allowNull: true
},
address: {
type: DataTypes.STRING,
allowNull: true
},
branch: {
type: DataTypes.STRING,
allowNull: true
},
create_date: {
type: DataTypes.DATE,
allowNull: true
},
update_date: {
type: DataTypes.DATE,
allowNull: true
}
}, {
tableName: 'm_bank',
timestamps: false,
schema: 'db_hrms'
});
};
on controllers/m_bank.js
const M_Bank = require('../models').m_bank;
module.exports = {
list(req, res) {
return M_Bank
.findAll()
.then(M_Bank => res.status(200).send(M_Bank))
.catch((error) => {
console.log(error.toString());
res.status(400).send(error)
});
},
getById(req, res) {
return M_Bank
.findById(req.params.id)
.then(M_Bank => {
if (!M_Bank) {
return res.status(404).send({ message: "M_Bank Not Found" });
}
return res.status(200).send(M_Bank);
})
.catch((error) => res.status(400).send(error));
},
add(req, res) {
return M_Bank
.findOrCreate({
where: { bank: req.body.bank },
defaults: {
bank: req.body.bank,
bank_name: req.body.bank_name,
address: req.body.address,
branch: req.body.branch
}
})
.spread((M_Bank, created) => {
return res.status(created === false ? 400 : 200).send({
messsage: "Bank record " + (created === false ? "Already exists" : "successfully added")
})
})
// .then((M_Bank) => { res.status(201).send(M_Bank) })
// .catch((error) => res.status(400).send(error));
},
update(req, res) {
return M_Bank
.findById(req.params.id)
.then(M_Bank => {
if (!M_Bank) {
return res.status(404).send({ message: "Bank Not Found" });
}
return M_Bank
.update({
bank: req.body.bank || M_Bank.bank,
bank_name: req.body.bank_name || M_Bank.bank_name,
address: req.body.address || M_Bank.address,
branch: req.body.branch || M_Bank.branch
})
.then(() => res.status(200).send({
message: "Bank successfully update"
}))
.catch((error) => res.status(400).send({
message: "Bank Not Found"
}));
})
.catch((error) => res.status(400).send({
message: "No parameter for Bank ID"
}));
},
delete(req, res) {
return M_Bank
.findById(req.params.id)
.then((M_Bank) => {
if (!M_Bank) {
return res.status(404).send({ message: "M_Bank Not Found" });
}
return M_Bank
.destroy()
.then(() => res.status(204).send({
message: "Bank record successfully delete"
}))
.catch((error) => res.status(400).send({
message: "Bank Not Found"
}));
})
.catch((error) => res.status(400).send(error));
}
}
on config/config.json configuration code:
{
"development": {
"username": "tihagi",
"password": "123456",
"database": "db_tihagi",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"username": "tihagi",
"password": "123456",
"database": "db_tihagi",
"host": "127.0.0.1",
"dialect": "postgres"
},
"production": {
"username": "tihagi",
"password": "123456",
"database": "db_tihagi",
"host": "127.0.0.1",
"dialect": "postgres"
}
}
Hope this can help you.
Note: my db is postgres, please change as per your dialect db.
-Tihagi
Possible reason could be that you didn't pass the model name correctly. What is the output of console.log(cust)
Change your customer model to this one.
/* jshint indent: 2 */
const db = require('../../db/database')
const sequelize = db.sequelize
module.exports = function(sequelize, DataTypes) {
var cust = sequelize.define('ms_customer', {
id: {
type: DataTypes.CHAR(10),
allowNull: false,
primaryKey: true
},
gender_id: {
type: DataTypes.INTEGER(1),
allowNull: true
},
status: {
type: DataTypes.CHAR(1),
allowNull: true
}
}, {
tableName: 'ms_customer'
});
return cust;
};
Your query to
const customerModel = require('../../db/model/ms_customer')
//const cust = customerModel.cust .... you do not need this.
module.exports = {
modelGetCustomerById : (param,req,res) => {
customerModel.findAll({
where: {
id: {
param
}
}
}).then(customer => {
// console.log(customer)
res.json(customer)
})
}
}