sequelize BulkCreate cannot read property 'set' of undefined - undefined

Recently I met some trouble when I was doing bulkCreate in Sequelize. I got the following error:
TypeError: Cannot read property 'set' of undefined
at results.forEach (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/lib/model.js:2357:27)
at Array.forEach (<anonymous>)
at QueryInterface.bulkInsert.then.results (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/lib/model.js:2356:21)
at tryCatcher (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/Users/mzd/Desktop/Shroogal/shroogal-dev/node_modules/sequelize/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:781:20)
at tryOnImmediate (timers.js:743:5)
at processImmediate [as _immediateCallback] (timers.js:714:5)
And this is my sequelize migration file:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('documentsInstruments', {
docid: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'docid'
},
iid: {
type: DataTypes.BIGINT,
allowNull: true,
references: {
model: 'EntityInstruments',
key: 'IID'
},
field: 'IID'
},
docType: {
type: DataTypes.STRING(45),
allowNull: true,
field: 'docType'
},
docPath: {
type: DataTypes.STRING(200),
allowNull: true,
field: 'docPath'
},
creationDate: {
type: DataTypes.DATE,
allowNull: true,
field: 'creationDate'
},
addlInfo: {
type: DataTypes.STRING(500),
allowNull: true,
field: 'addlInfo'
},
posLabel: {
type: DataTypes.STRING(45),
allowNull: true,
field: 'posLabel'
},
active: {
type: DataTypes.STRING(3),
allowNull: true,
defaultValue: 'Y',
field: 'active'
},
origFileName: {
type: DataTypes.STRING(400),
allowNull: true,
field: 'origFileName'
}
}, {
tableName: 'Documents_Instruments'
});
};
And this is my bulkCreate function:
if(obj.documents) {
let data = [];
obj.documents.forEach((v, i) => {
var d = {};
if(v.docid)
d.docid = v.docid;
if(obj.iid)
d.iid = obj.iid;
if(v.type)
d.docType = v.type;
if(v.filePath)
d.docPath = v.filePath;
if(v.date)
d.creationDate = v.date;
if(v.additionalDescription)
d.addlInfo = v.additionalDescription;
if(v.originalName)
d.origFileName = v.originalName;
data.push(d);
});
this.documentsInstruments
.bulkCreate(data, {
updateOnDuplicate: ['docType', 'docPath', 'creationDate', 'addlInfo', 'origFileName']
})
.then((d) => {
resolve(d);
})
.catch((err) => {
reject(err);
});
}
I check the source code(node_modules/sequelize/lib/model.js:2357:27) and try to print something for debugging, the instance[i] become undefine in this.QueryInterface.bulkInsert functions

I got same issue you had and I couldn't find out why that error raised too.
But When i upgrade sequelize library version from v4.4.2 to 4.11.0, and then that error doesn't show up anymore.
If your version is not latest, try upgrade version.

Related

How to define an array in my models using mysql sequelize | node.js

This is the result what I need to store in DB :
sellers : [{'test1'},{'test2'},{'test3'}]
And this is my model:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"User",
{
id: {
allowNull: false,
primaryKey: true,
autoIncrement: true,
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
sellers: [
{
type: DataTypes.STRING,
allowNull: true,
},
],
},
{
timestamps: true,
defaultScope: {
attributes: {
exclude: ["password"],
},
},
scopes: {
withPassword: {
attributes: {},
},
},
indexes: [
{
unique: true,
fields: ["email"],
},
],
}
);
return User;
};
And the error is :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
sellers: [
{
type: DataTypes.ARRAY(DataTypes.STRING),
allowNull: true,
}
You need to slightly change your schema definition as,
sellers: {
type: DataTypes.ARRAY(DataTypes.JSON),
allowNull: true,
defaultValue: [{}],
get() {
const data = this.getDataValue('sellers');
const queryResponse = [];
data.forEach(seller => {
queryResponse.push(JSON.parse(seller));
});
return queryResponse;
},
set(seller) {
return this.setDataValue('sellers', JSON.stringify(seller));
}
},

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 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 model prototype show add function, but fails when executed

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

Sequelize error on model.update

Unhandled rejection TypeError: undefined is not a function
error whe i am trying to update my table in sequelize above MySQL.
here is the snippet of code that triggering the error with commented one that surprisingly works:
topic.update(
{ name: "adfa"},
{ where: { tid: 1} }
);
//topicAttribute.update({ value: "name 2"},{where: {TOPIC: 2,name: "nadpis" }});
Now this is my two models:
var topic = sequelize.define('topic', {
tid: { type: Sequelize.INTEGER,
field: 'tid',
primaryKey: true
},
name: { type: Sequelize.STRING,
field: 'name'
},
added: { type: Sequelize.DATE,
field: 'added'
},
addedBy: { type: Sequelize.STRING,
field: 'added_by'
},
changed: { type: Sequelize.DATE,
field: 'changed'
},
changedBy: { type: Sequelize.STRING,
field: 'changed_by'
},
parent: { type: Sequelize.INTEGER,
field: 'parent'
},
enabled: {
type: Sequelize.BOOLEAN,
field: 'enabled'
}
},
{
tableName: 'topic',
timestamps: false
});
var topicAttribute = sequelize.define('tAttribute', {
parent: { type: Sequelize.INTEGER,
field: 'TOPIC',
primaryKey: true
},
name: { type: Sequelize.STRING,
field: 'name',
primaryKey: true
},
value: { type: Sequelize.STRING,
field: 'value'
},
},
{
tableName: 'topic_attribute',
timestamps: false
});
topic.hasOne(topic, {foreignKey: 'tid'});
topic.hasMany(topicAttribute, {foreignKey: 'parent'});
topicAttribute.belongsTo(topic, {foreignKey: 'parent'});
And finally my stacktrace:
Unhandled rejection TypeError: undefined is not a function
at Instance.set (C:\Users\212443162\Documents\ithd\node_modules\sequelize\lib\instance.js:365:16)
at Instance.set (C:\Users\212443162\Documents\ithd\node_modules\sequelize\lib\instance.js:293:16)
at initValues (C:\Users\212443162\Documents\ithd\node_modules\sequelize\lib\instance.js:63:8)
at Instance (C:\Users\212443162\Documents\ithd\node_modules\sequelize\lib\instance.js:107:14)
at new Instance (C:\Users\212443162\Documents\ithd\node_modules\sequelize\li b\model.js:655:14)
at Model.build (C:\Users\212443162\Documents\ithd\node_modules\sequelize\lib\model.js:1493:10)
at C:\Users\212443162\Documents\ithd\node_modules\sequelize\lib\model.js:2119:24
at tryCatcher (C:\Users\212443162\Documents\ithd\node_modules\sequelize\node_modules\bluebird\js\main\util.js:24:31)
at Function.Promise.attempt.Promise.try (C:\Users\212443162\Documents\ithd\node_modules\sequelize\node_modules\bluebird\js\main\method.js:31:24)
at Model.update (C:\Users\212443162\Documents\ithd\node_modules\sequelize\li b\model.js:2116:21)
at C:\Users\212443162\Documents\ithd\routes\topics.js:119:8 at Layer.handle [as handle_request] (C:\Users\212443162\Documents\ithd\node_ modules\express\lib\router\layer.js:95:5)
at next (C:\Users\212443162\Documents\ithd\node_modules\express\lib\router\r oute.js:131:13)
at Route.dispatch (C:\Users\212443162\Documents\ithd\node_modules\express\li b\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\212443162\Documents\ithd\node_ modules\express\lib\router\layer.js:95:5)
at C:\Users\212443162\Documents\ithd\node_modules\express\lib\router\index.j s:277:22