Cannot read property 'findAll' of undefined sequelize express JS
up vote
1
down vote
favorite
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..
javascript mysql node.js express sequelize.js
add a comment |
up vote
1
down vote
favorite
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..
javascript mysql node.js express sequelize.js
Hey Man, can I have your kind feedback on my answer ? Thanks,
– bereket gebredingle
Nov 11 at 3:58
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
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..
javascript mysql node.js express sequelize.js
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..
javascript mysql node.js express sequelize.js
javascript mysql node.js express sequelize.js
edited Nov 9 at 10:53
Prashant Gupta
741519
741519
asked Nov 9 at 10:01
Agung hallman maliki
145
145
Hey Man, can I have your kind feedback on my answer ? Thanks,
– bereket gebredingle
Nov 11 at 3:58
add a comment |
Hey Man, can I have your kind feedback on my answer ? Thanks,
– bereket gebredingle
Nov 11 at 3:58
Hey Man, can I have your kind feedback on my answer ? Thanks,
– bereket gebredingle
Nov 11 at 3:58
Hey Man, can I have your kind feedback on my answer ? Thanks,
– bereket gebredingle
Nov 11 at 3:58
add a comment |
3 Answers
3
active
oldest
votes
up vote
1
down vote
accepted
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
add a comment |
up vote
0
down vote
Possible reason could be that you didn't pass the model name correctly. What is the output of console.log(cust)
add a comment |
up vote
0
down vote
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)
})
}
}
i got the same errors
– Agung hallman maliki
Nov 11 at 13:59
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53223559%2fcannot-read-property-findall-of-undefined-sequelize-express-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
1
down vote
accepted
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
add a comment |
up vote
1
down vote
accepted
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
add a comment |
up vote
1
down vote
accepted
up vote
1
down vote
accepted
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
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
answered Nov 12 at 6:11
ManzTIHAGI
282
282
add a comment |
add a comment |
up vote
0
down vote
Possible reason could be that you didn't pass the model name correctly. What is the output of console.log(cust)
add a comment |
up vote
0
down vote
Possible reason could be that you didn't pass the model name correctly. What is the output of console.log(cust)
add a comment |
up vote
0
down vote
up vote
0
down vote
Possible reason could be that you didn't pass the model name correctly. What is the output of console.log(cust)
Possible reason could be that you didn't pass the model name correctly. What is the output of console.log(cust)
answered Nov 9 at 16:55
Pathum Samararathna
678419
678419
add a comment |
add a comment |
up vote
0
down vote
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)
})
}
}
i got the same errors
– Agung hallman maliki
Nov 11 at 13:59
add a comment |
up vote
0
down vote
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)
})
}
}
i got the same errors
– Agung hallman maliki
Nov 11 at 13:59
add a comment |
up vote
0
down vote
up vote
0
down vote
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)
})
}
}
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)
})
}
}
answered Nov 10 at 9:03
bereket gebredingle
853616
853616
i got the same errors
– Agung hallman maliki
Nov 11 at 13:59
add a comment |
i got the same errors
– Agung hallman maliki
Nov 11 at 13:59
i got the same errors
– Agung hallman maliki
Nov 11 at 13:59
i got the same errors
– Agung hallman maliki
Nov 11 at 13:59
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53223559%2fcannot-read-property-findall-of-undefined-sequelize-express-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Hey Man, can I have your kind feedback on my answer ? Thanks,
– bereket gebredingle
Nov 11 at 3:58