Sequelize model prototype show add function, but fails when executed - mysql

I am having trouble adding users to my boards model using sequelize. My associations are defined as follows:
module.exports = function(sequelize, DataTypes) {
var Board = sequelize.define("Board", {
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
favorited: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
}
});
Board.associate = function(models) {
Board.belongsTo(models.User, {
foreignKey: {
name: "OwnerId"
}
});
Board.belongsToMany(models.User, {
through: "UserBoards"
});
};
return Board;
};
And my user model:
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isAlphanumeric: true
}
},
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
}
});
User.associate = function(models) {
User.belongsToMany(models.Board, {
through: "UserBoards"
});
};
return User;
};
Console logging Boards.prototype gives me the following:
Board {
_customGetters: {},
_customSetters: {},
validators: { name: { len: [Object] } },
_hasCustomGetters: 0,
_hasCustomSetters: 0,
rawAttributes:
{ id:
{ type: [Object],
allowNull: false,
primaryKey: true,
autoIncrement: true,
_autoGenerated: true,
Model: Board,
fieldName: 'id',
_modelAttribute: true,
field: 'id' },
name:
{ type: [Object],
allowNull: false,
validate: [Object],
Model: Board,
fieldName: 'name',
_modelAttribute: true,
field: 'name' },
favorited:
{ type: BOOLEAN {},
allowNull: false,
defaultValue: false,
Model: Board,
fieldName: 'favorited',
_modelAttribute: true,
field: 'favorited' },
createdAt:
{ type: [Object],
allowNull: false,
_autoGenerated: true,
Model: Board,
fieldName: 'createdAt',
_modelAttribute: true,
field: 'createdAt' },
updatedAt:
{ type: [Object],
allowNull: false,
_autoGenerated: true,
Model: Board,
fieldName: 'updatedAt',
_modelAttribute: true,
field: 'updatedAt' },
OwnerId:
{ name: 'OwnerId',
type: [Object],
allowNull: true,
references: [Object],
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
Model: Board,
fieldName: 'OwnerId',
_modelAttribute: true,
field: 'OwnerId' } },
attributes: [ 'id', 'name', 'favorited', 'createdAt', 'updatedAt', 'OwnerId' ],
_isAttribute: { [Function: memoized] cache: MapCache { size: 0, __data__: [Object] } },
getUser: [Function],
setUser: [Function],
createUser: [Function],
getUsers: [Function],
countUsers: [Function],
hasUser: [Function],
hasUsers: [Function],
setUsers: [Function],
addUser: [Function],
addUsers: [Function],
removeUser: [Function],
removeUsers: [Function] }
But when I try to runt he following in my routes it says that addUser/addUsers are not functions:
router.get("/boards/:id/users/:uid", function(req, res) {
var query = {};
if (req.params.id) {
query.id = req.params.id;
db.Board.findAll({
where: query
}).then(function(dbBoard) {
dbBoard.addUser(req.params.uid);
res.json(dbBoards);
});
}
});
Any help would be appreciated. Thank you.

Adding an association is instance specific. You have to call this method on a single instance of the Board model. For example:
const singleBoard = db.board.findOne({where: query};
const user = db.users.findOne({where: {id: parseInt(req.params.uid)});
singleBoard.addUser(user);
You can iterate through the array you get from querying through findAll if you have to do the same operation on multiple boards.
https://sequelize.org/master/manual/advanced-many-to-many.html

Related

Could not find migration method: up

I am unable to migrate my models to MySQL db. It's throwing me the below error:
Loaded configuration file "config\config.json".
Using environment "development".
(node:5828) [SEQUELIZE0004] DeprecationWarning: A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed.
== 20191218125700-mig_admin_roles: migrating =======
ERROR: Could not find migration method: up
models- admin_user.js
module.exports = (sequelize, DataTypes) => {
{
var admin_users = sequelize.define("adminUser", {
id: {
type: DataTypes.INTEGER(22),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: "id"
},
fname: {
type: DataTypes.STRING(20),
allowNull: false,
field: "fname"
},
lname: {
type: DataTypes.STRING(20),
allowNull: true,
field: "lname"
},
phoneNo: {
type: DataTypes.STRING(20),
allowNull: false,
field: "phoneNo"
},
emailId: {
type: DataTypes.STRING(20),
allowNull: false,
unique: true,
field: "emailId"
},
isActive: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: "0",
field: "isActive"
},
password: {
type: DataTypes.STRING(128),
allownull: false,
field: "password"
}
});
admin_users.associate = models => {
admin_users.hasMany(models.adminRole, {
foreignKey: "roleId"
});
};
return admin_users;
}
};
migration: mig-admin_user.js
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable("adminUser", {
id: {
type: Sequelize.INTEGER(22),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: "id"
},
fname: {
type: Sequelize.STRING(20),
allowNull: false,
field: "fname"
},
lname: {
type: Sequelize.STRING(20),
allowNull: true,
field: "lname"
},
phoneNo: {
type: Sequelize.STRING(20),
allowNull: false,
field: "phoneNo"
},
emailId: {
type: Sequelize.STRING(20),
allowNull: false,
unique: true,
field: "emailId"
},
isActive: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: "0",
field: "isActive"
},
password: {
type: Sequelize.STRING(128),
allownull: false,
field: "password"
}
});
},
down: (queryInterface, Sequelize) => {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.dropTable('users');
*/
}
};
I tried looking for this particular error, but couldn't find anything.
could anyone please tell where i might be going wrong?
You need a .sequelizerc in the root of your project and it contains something like this :
module.exports = {
'config': 'database/config.js',
'migrations-path': 'database/migrations',
'seeders-path': 'database/seeders'
}
And you have to point where are your migrations been located.

Sequelize: Unable to set reference to two different tables after migrations

I am trying to set reference from donorslist table to user table and requestblood table. Though the references columns(userid, requestbloodid) are getting added to the table, it is failing to insert the reference id 'requestbloodid' in the column and sets it to NULL.
I am using
Nodejs
mysql: 2.16.0 v
sequelize: 4.37.10 v
user.js model file:
const moment = require('moment');
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define(
'user',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
fullname: {
type: DataTypes.STRING(20),
allowNull: false,
},
gender: { type: DataTypes.CHAR(1), allowNull: false },
latitude: {
type: DataTypes.DECIMAL(20, 15),
allowNull: false,
validate: { min: -90, max: 90 },
},
longitude: {
type: DataTypes.DECIMAL(20, 15),
allowNull: false,
validate: { min: -180, max: 180 },
},
email: {
type: DataTypes.STRING(50),
allowNull: true,
},
isglobalcontactshared: { type: DataTypes.BOOLEAN, defaultValue: false },
createdAt: {
type: DataTypes.DATE,
get() {
return moment.utc(new Date(), 'DD-MMM-YYYY h:mm a').format('DD-MMM-YYYY h:mm a');
},
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: null,
},
},
{
freezeTableName: true,
}
);
user.associate = function(models) {
user.belongsTo(models.contactdetails, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'contactdetailid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
return user;
};
requestblood.js file:
const moment = require('moment');
module.exports = (sequelize, DataTypes) => {
const requestblood = sequelize.define(
'requestblood',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
requestid: {
type: DataTypes.STRING(10),
allowNull: false,
},
latitude: {
type: DataTypes.DECIMAL(20, 15),
allowNull: false,
validate: { min: -90, max: 90 },
},
longitude: {
type: DataTypes.DECIMAL(20, 15),
allowNull: false,
validate: { min: -180, max: 180 },
},
locality: { type: DataTypes.STRING(20), allowNull: false },
city: { type: DataTypes.STRING, allowNull: false },
bloodtype: {
type: DataTypes.INTEGER,
allowNull: false,
isNumeric: true,
validate: { min: 1, max: 9 },
},
duedate: {
type: DataTypes.DATEONLY,
allowNull: false,
get() {
return moment.utc(this.getDataValue('duedate')).format('DD-MMM-YYYY');
},
},
unitsrequired: { type: DataTypes.INTEGER, isNumeric: true },
description: { type: DataTypes.STRING(500) },
requeststateid: { type: DataTypes.STRING, allowNull: false },
createdAt: {
type: DataTypes.DATE,
get() {
return moment.utc(new Date(), 'DD-MMM-YYYY h:mm a').format('DD-MMM-YYYY h:mm a');
},
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: null,
},
},
{
freezeTableName: true,
}
);
requestblood.associate = function(models) {
requestblood.belongsTo(models.contactdetails, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'contactdetailid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
/* requestblood.associate = function(models) {
requestblood.hasMany(models.donorslist, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'requestbloodid',
allowNull: false,
foreignKeyConstraint: true,
},
});
}; */
return requestblood;
};
donorslist.js file
const moment = require('moment');
module.exports = (sequelize, DataTypes) => {
const donorslist = sequelize.define(
'donorslist',
{
id: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4,
},
fullname: {
type: DataTypes.STRING(20),
allowNull: false,
},
bloodgroup: { type: DataTypes.INTEGER, allowNull: false },
contactnumber: { type: DataTypes.STRING(13), allowNull: true },
willdonate: { type: DataTypes.BOOLEAN, defaultValue: false },
hasdonated: { type: DataTypes.BOOLEAN, defaultValue: false },
createdAt: {
type: DataTypes.DATE,
get() {
return moment.utc(new Date(), 'DD-MMM-YYYY h:mm a').format('DD-MMM-YYYY h:mm a');
},
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: null,
},
},
{
freezeTableName: true,
}
);
donorslist.associate = function(models) {
donorslist.belongsTo(models.requestblood, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'requestbloodid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
donorslist.associate = function(models) {
donorslist.belongsTo(models.user, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'userid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};
return donorslist;
};
When the below code is executed,
models.donorslist
.create({
fullname,
bloodgroup: bloodgrp,
contactnumber: contnum,
willdonate: req.body.willdonate,
userid: usrid,
requestbloodid: reqid,
updatedAt: null,
})
`
it returns the query as:
INSERT INTO `donorslist` (`id`,`fullname`,`bloodgroup`,`contactnumber`,`willdonate`,`hasdonated`,`createdAt`,`updatedAt`,`userid`) VALUES ('687888be-4381-460f-af62-46365a16fb40','sunil',4,'+123456789',true,false,'2019-01-10 07:00:12','2019-01-10 07:00:12','b93cfd73-a6ea-4825-91ad-8ded37418ca7');
Note the missing requestbloodid column. It somehow skips the requestbloodid column. I am facing this issue, after performing migrations. This was working fine with sequelize.sync(). If i uncomment the below code in requestblood.js file, then the referenceid 'contactdetailid' of requestblood table is set as NULL. So, i am unable to make a reference of belongsTo and hasMany from these two tables.
requestblood.associate = function(models) {
requestblood.hasMany(models.donorslist, {
onDelete: 'CASCADE',
hooks: true,
foreignKey: {
name: 'requestbloodid',
allowNull: false,
foreignKeyConstraint: true,
},
});
};

Can i use `SET` variable in sequelize in nodejs

Can i use SET variable in sequelize in nodejs?
Sequelize
Model
Session Model
"use strict";
module.exports = (sequelize, DataTypes) => {
const Sessions = sequelize.define(
"sessions",
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
challenge_id: {
type: DataTypes.INTEGER,
references: {
model: "challenges",
key: "id"
},
allowNull: false
},
createdAt: { type: DataTypes.DATE },
createdBy: {
type: DataTypes.INTEGER,
references: {
model: "users",
key: "id"
},
allowNull: false
},
showAtLeaderboard: { type: DataTypes.ENUM("yes", "no") },
sessionFile: { type: DataTypes.STRING },
score: { type: DataTypes.INTEGER },
},
{
timestamps: false,
underscored: true
}
);
return Sessions;
};
Challenge Model
"use strict";
module.exports = (sequelize, DataTypes) => {
const Challenges = sequelize.define(
"challenges",
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
song_id: { type: DataTypes.INTEGER },
challenge_name: { type: DataTypes.STRING },
challengeDescription: { type: DataTypes.STRING },
challengeImg: { type: DataTypes.STRING },
challengeType: { type: DataTypes.STRING },
coins: { type: DataTypes.INTEGER },
createdAt: { type: DataTypes.DATE },
expireAt: { type: DataTypes.DATE },
isActive: { type: DataTypes.ENUM("yes", "no") },
tags: { type: DataTypes.STRING }
},
{
timestamps: false,
underscored: true
}
);
return Challenges;
};
Relationship
db.challenges.hasMany(db.sessions, {
foreignKey: "challenge_id",
sourceKey: "id"
});
Can I perform below SQL query with sequelize Orm model?
SET #rank=0
SELECT `challenges`.`*`, `sessions`.*, #rank:=#rank+1 AS rank FROM `challenges` JOIN `sessions` ON `sessions`.`challenge_id` = `challenges`.`id` ORDER BY `sessions`.`score` DESC
Sequelize support this type of query with it's ORM Model.

Sequelize belongsToMany not working

Here is my problem:
Table WO -> sparepart_request -> sparepart.
A work order have several sparepart and sparepart can belong to several WO.
This is my code in wo.js (sequelize model)
models.sparepart.belongsToMany(models.wo, { as: 'SPWO', through: 'sparepart_request', foreignKey: 'codSparePart' });
This is my code in sparepart.js (sequelize model).
models.sparepart.belongsToMany(models.wo, { as: 'SPWO', through: 'sparepart_request', foreignKey: 'codSparePart' });
In sparepart_request there is nothing about associations. I've followed the next instructions Sequelize
In my query I have the next code:
exports.readDetailWO = function (req, res) {
models.wo.findAll({
attributes: ['codWO'], // attributes: ['id', 'codWO', 'codSparePart', 'quantity', 'date_request', 'date_reception', 'details', 'codUser', 'received'],
raw: true,
where: {
codWO: req.params.codWO
},
include: [{
model: models.sparepart,
attributes: ['codSparePart', 'name', 'description', 'codManufacturer', 'image_uri', 'stock'],
paranoid: false,
required: false,
as: 'SPWO'
}]
}).then(sparePart => {
if (!sparePart) {
res.status(404);
res.send({
success: false,
message: 'Spare Part not found. ' + req.params.codWO,
data: sparePart
});
} else if (sparePart) {
res.json({
success: true,
message: 'Spare Part found.',
data: sparePart
});
}
}).catch(function (error) {
logger.error(JSON.stringify(error));
res.json({
message: 'Query not successful and error has occured reading',
error: error,
stackError: error.stack
});
return res.status(500);
});
};
But the server's response (using PostMan) is the following:
{
"message": "Query not successful and error has occured reading",
"error": {
"name": "SequelizeEagerLoadingError"
},
"stackError": "SequelizeEagerLoadingError: sparepart is not associated to wo!\n
AS I have been able to read here that maybe the problem that is my primaryKeys are not name id, but now I can change these names...
Where is the problem? Thanks in advance for your help.
Model sparepart_request.js
module.exports = function (sequelize, DataTypes) {
var sparepart_request = sequelize.define('sparepart_request', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
codWo: {
type: DataTypes.STRING(20),
allowNull: false,
foreignKey: {
model: 'wo',
key: 'codWO'
}
},
codSparePart: {
type: DataTypes.STRING(30),
allowNull: false,
references: {
model: 'sparepart',
key: 'codSparePart'
}
},
quantity: {
type: DataTypes.FLOAT,
allowNull: true
},
date_request: {
type: DataTypes.DATEONLY,
allowNull: true
},
date_reception: {
type: DataTypes.DATEONLY,
allowNull: true
},
details: {
type: DataTypes.TEXT,
allowNull: true
},
codUser: {
type: DataTypes.STRING(20),
allowNull: false,
references: {
model: 'user',
key: 'codUser'
}
},
received: {
type: DataTypes.INTEGER(1),
allowNull: false
}
}, {
tableName: 'sparepart_request',
timestamps: false
});
/* sparepart_request.associate = function (models) {
models.sparepart_request.hasMany(models.sparepart, {foreignKey: 'codSparePart', targetKey: 'codSparePart'});
}; */
return sparepart_request;
};
Model wo.js:
/* jshint indent: 1 */
module.exports = function (sequelize, DataTypes) {
var wo = sequelize.define('wo', {
codWO: {
type: DataTypes.STRING(20),
allowNull: false,
primaryKey: true
},
codUser: {
type: DataTypes.STRING(20),
allowNull: false,
references: {
model: 'user',
key: 'codUser'
}
},
codOriginator: {
type: DataTypes.STRING(20),
allowNull: true,
references: {
model: 'user',
key: 'codUser'
}
},
capture_date: {
type: DataTypes.DATE,
allowNull: false
},
active: {
type: DataTypes.INTEGER(1),
allowNull: false
},
codType: {
type: DataTypes.CHAR(3),
allowNull: false,
references: {
model: 'type',
key: 'codType'
}
},
date: {
type: DataTypes.DATEONLY,
allowNull: false
},
title: {
type: DataTypes.STRING(255),
allowNull: true
},
date_finish: {
type: DataTypes.DATEONLY,
allowNull: true
},
codStatus: {
type: DataTypes.STRING(10),
allowNull: false,
references: {
model: 'status',
key: 'codStatus'
}
},
hours_planned: {
type: DataTypes.FLOAT,
allowNull: true
},
codElement: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'element',
key: 'codElement'
}
},
Security: {
type: DataTypes.INTEGER(1),
allowNull: true,
defaultValue: '0'
},
codEquipment: {
type: DataTypes.STRING(20),
allowNull: false,
references: {
model: 'equipment',
key: 'codEquipment'
}
},
codProject: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'project',
key: 'id'
}
},
codTestRoom: {
type: DataTypes.STRING(10),
allowNull: false,
references: {
model: 'testroom',
key: 'codTestRoom'
}
}
}, {
tableName: 'wo',
timestamps: false
});
wo.associate = function (models) {
models.wo.belongsTo(models.wo_operation, {
as: 'wo_operation',
foreignKey: {
name: 'codWO',
allowNull: false
},
targetKey: 'codWO'
});
models.wo.belongsTo(models.dailyinfo_detail, {
as: 'dailyInfo',
foreignKey: {
name: 'codWO',
allowNull: false
},
targetKey: 'codWO'
});
models.wo.hasOne(models.wo_corrective, {
as: 'wo_corrective',
foreignKey: {
name: 'codWO',
allowNull: false
},
targetKey: 'codWO'
});
models.wo.hasOne(models.wo_preventive, {
as: 'wo_preventive',
foreignKey: {
name: 'codWO',
allowNull: false
},
targetKey: 'codWO'
});
models.wo.belongsToMany(models.sparepart_request, { as: 'WOSP', through: 'sparepart_request', foreignKey: 'codWO', otherKey: 'codSparePart' });
};
return wo;
};
Model sparepart.js
/* jshint indent: 1 */
module.exports = function (sequelize, DataTypes) {
var sparepart = sequelize.define('sparepart', {
codSparePart: {
type: DataTypes.STRING(30),
allowNull: false,
primaryKey: true,
references: {
model: 'sparepart_request',
key: 'codSparePart'
}
},
name: {
type: DataTypes.STRING(45),
allowNull: true
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
available: {
type: DataTypes.INTEGER(1),
allowNull: false,
defaultValue: '1'
},
codManufacturer: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'manufacturer',
key: 'codManufacturer'
}
},
stock: {
type: DataTypes.INTEGER(10),
allowNull: true
},
image_uri: {
type: DataTypes.STRING(500),
allowNull: true
},
codProject: {
type: DataTypes.INTEGER(11),
allowNull: true,
references: {
model: 'project',
key: 'id'
}
},
price: {
type: DataTypes.FLOAT,
allowNull: false
}
}, {
tableName: 'sparepart',
timestamps: false
});
sparepart.associate = function (models) {
models.sparepart.belongsTo(models.manufacturer, {
foreignKey: 'codManufacturer',
targetKey: 'codManufacturer'
});
models.sparepart.belongsToMany(models.wo, { as: 'SPWO', through: 'sparepart_request', foreignKey: 'codSparePart', otherKey: 'codWO' });
};
return sparepart;
};
Here you can find my code, the three models and the query. at the moment I'm using postman I don't have anything in the frontEnd.
Here is one solution:
Remove id from sparepart_request.
Include the next code in sparepart_request:
sparepart_request.associate = function (models) {
models.sparepart_request.hasMany(models.sparepart, {foreignKey: 'codSparePart', targetKey: 'codSparePart'});
models.sparepart_request.hasMany(models.wo, {foreignKey: 'codWO', targetKey: 'codWO'});
};
Is it the correct way to do?, Apparently it is working...

Sequelize says instanceMethod is not defined

I'm using sequelize to connect to a mysql db for development. I have a model called Dealer:
'use strict';
module.exports = function(sequelize, DataTypes) {
var Dealer = sequelize.define('Dealer', {
id: { allowNull: false, autoIncrement: true,
primaryKey: true, type: DataTypes.INTEGER.UNSIGNED },
...
created_at: { allowNull: false, type: DataTypes.DATE },
updated_at: { allowNull: false, type: DataTypes.DATE }
},
{underscored: true},
{
classMethods: {
associate: function(models) {
Dealer.hasMany(models.Job);
}
},
instanceMethods: {
getAllClientData: function(){
leads = [];
...
return leads;
},
}
});
return Dealer;
};
When I try to call the instance method on an object returned by a sequelize query in my dealerController.js file:
dealer.getAllClientData()
I get the error:
Unhandled rejection TypeError: dealer.getAllClientData is not a function
When i print the returned JSON to the console it reads as such:
{ dataValues:
{ id: 1,
....
}
...
'$modelOptions':
{ timestamps: true,
instanceMethods: {},
classMethods: {},
validate: {},
freezeTableName: false,
underscored: true,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: { id: '1' },
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
hooks: {},
indexes: [],
name: { plural: 'Dealers', singular: 'Dealer' },
omitNul: false,
...
}
...
}
Obviously my instanceMethod is not defined, and according to the sequelize docs I should have getters and setters available too.
I don't understand what step i'm missing here as I've read through much of the sequelize docs and even used their cli to generate the models and migrations.
Any thoughts?
Edit:
Here is what is output to log for dealer.prototype
{ _customGetters: {},
_customSetters: {},
validators: {},
_hasCustomGetters: 0,
_hasCustomSetters: 0,
rawAttributes:
{ id:
{ allowNull: false,
autoIncrement: true,
primaryKey: true,
type: [Object],
Model: Dealer,
fieldName: 'id',
_modelAttribute: true,
field: 'id' },
///Other Attributes
},
_isAttribute: { [Function] cache: MapCache { __data__: [Object] } },
Model: Dealer,
$Model': Dealer }
After reading the docs a little further and looking at some other model definitions I discovered that the issue was I had defined my model incorrectly.
In my definition above you'll notice I wrapped the underscored: true option in brackets, followed by my classMethods and instanceMethods wrapped in another set of brackets.
This is incorrect. The proper way to define a sequelize model is with two sets of brackets, the first containing your model attributes and the second containing all other options, including methods.
'use strict';
module.exports = function(sequelize, DataTypes) {
var Dealer = sequelize.define('Dealer', {
id: { allowNull: false, autoIncrement: true,
primaryKey: true, type: DataTypes.INTEGER.UNSIGNED },
...
created_at: { allowNull: false, type: DataTypes.DATE },
updated_at: { allowNull: false, type: DataTypes.DATE }
},
{
underscored: true,
classMethods: {
associate: function(models) {
Dealer.hasMany(models.Job);
}
},
instanceMethods: {
getAllClientData: function(){
leads = [];
...
return leads;
},
}
});
return Dealer;
};