why model not fetching all attributes in table in sequelize - mysql

I have created model for my databse and then run migration it successfully created the table in database after this I create migration to add column to that existing table . When I run model.findall query it only gets the attributes that I created first time e.g here is my model file
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('ActiveUsers', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
username: {
type: Sequelize.STRING
},
name: {
type: Sequelize.STRING
},
socketId: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('ActiveUsers');
}
};
here is migration file to add column to this table
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
queryInterface.addColumn(
'ActiveUsers',
'Token',
{
type: Sequelize.STRING,
allowNull: false
}
)
},
down: (queryInterface, Sequelize) => {
}
};
here is table pic
it only gets the attributes that are present in model file i.e
username,name,socketId,updatedAt,createdAt
why it dont get the value of
token,status
here is my code
activeusers.findAll({raw:true}).then(Users=>{
console.log('online users')
})

The first file you wrote is not a model file, it is a migration file. If you want to select your new fields you should add them to your model file.
Your model file should look like this:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('activeUsers', {
id: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
unique: true
},
username: {
type: Sequelize.STRING
},
name: {
type: Sequelize.STRING
},
socketId: {
type: Sequelize.STRING
},
token: {
type: Sequelize.STRING
},
status: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
};
You can read more in Sequelize docs about how to add models to your project.

We have to add column fields to model file manually . then it will fetch that fields

Related

Sequelize UUID with mySQL: Unable to set default value

I've been trying for awhile to set id (primary key) for my Users table as UUID. However, I keep getting this error: Field 'id' doesn't have a default value, when I attempt to seed it.
This is what I have so far in my Users model:
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Users extends Model {};
Users.init({
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true
},
user_name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: {
msg: 'Please add a name',
},
},
},
{
sequelize,
modelName: 'Users',
});
return Users;
Likewise, this is what I have in my Users migration file:
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Admins', {
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
allowNull: false,
primaryKey: true
},
user_name: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Users');
}
};
I'm pretty new to Sequelize, so would love some guidance on what's gone wrong!
By adding defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), to your createdAt and updatedAt in your migration file defaults the value to the current timestamp.
createdAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
},
So, I think I realised the issue:
For some reason, seeding it by using a seeder file would not auto-generate the fields that I thought would be auto-generated, so I had to put them in manually.
'use strict';
const { v4: uuidv4 } = require('uuid');
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.bulkInsert('Users', [{
id: uuidv4(),
user_name: 'John Doe',
"createdAt": new Date(),
"updatedAt": new Date()
}], {});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete('Users', null, {});
}
};
Initially, I had been trying to seed (running the command npx sequelize-cli db:seed:all) without the id: uuidv4() and the new Date(), which was why it didn't work.

ERROR: Cannot find module 'sequelize/types'

C:\Users\lenovo\Desktop\Yoobou\Yoobou>sequelize db:migrate
Sequelize CLI [Node: 14.15.1, CLI: 6.2.0, ORM: 6.3.5]
Loaded configuration file "config\config.json". Using environment
"development".
== 20201207141344-create-producteurs: migrating =======
ERROR: Cannot find module 'sequelize/types' Require stack:
C:\Users\lenovo\Desktop\Yoobou\Yoobou\migrations\20201207141344-create-producteurs.js
C:\Users\lenovo\AppData\Roaming\npm\node_modules\sequelize-cli\node_modules\umzug\lib\migration.js
C:\Users\lenovo\AppData\Roaming\npm\node_modules\sequelize-cli\node_modules\umzug\lib\index.js
C:\Users\lenovo\AppData\Roaming\npm\node_modules\sequelize-cli\lib\core\migrator.js
C:\Users\lenovo\AppData\Roaming\npm\node_modules\sequelize-cli\lib\commands\migrate.js
C:\Users\lenovo\AppData\Roaming\npm\node_modules\sequelize-cli\lib\sequelize
//MIGRATION 20201207141344-create-producteurs.js
'use strict'; const { UniqueConstraintError } =
require('sequelize/types');
module.exports = { up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('PRODUCTEURS', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
first_name: {
allowNull: false,
type: Sequelize.STRING,
unique: true,
},
last_name: {
allowNull: false,
type: Sequelize.STRING,
},
email: {
allowNull: false,
type: Sequelize.STRING,
Unique: true,
},
password: {
allowNull: false,
type: Sequelize.STRING,
},
avatar: {
allowNull: false,
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
}); }, down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('PRODUCTEURS'); }, };
// ASSOCIATION MODELS 'use strict'; const { Model } = require('sequelize'); module.exports = (sequelize, DataTypes) => {
class ADMINISTRATEUR extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The models/index file will call this method automatically.
/
associate(models) {
// define association here
models.ADMINISTRATEUR.hasMany(models.CLIENTS);
models.ADMINISTRATEUR.hasMany(models.PRODUITS);
models.ADMINISTRATEUR.hasMany(models.ADRESSE_CLIENTS);
models.ADMINISTRATEUR.hasMany(models.CATEGORY_PRODUITS);
models.ADMINISTRATEUR.hasMany(models.COMMANDES);
models.ADMINISTRATEUR.hasMany(models.PRODUCTEURS);
models.ADMINISTRATEUR.hasMany(models.AVIS);
} } ADMINISTRATEUR.init(
{
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
avatar: DataTypes.STRING,
},
{
sequelize,
modelName: 'ADMINISTRATEUR',
} ); return ADMINISTRATEUR; }; 'use strict'; const { Model } = require('sequelize'); module.exports = (sequelize, DataTypes) =>
{ class PRODUCTEURS extends Model {
/*
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The models/index file will call this method automatically.
*/
static associate(models) {
// define association here
models.PRODUCTEURS.belongsTo(models.ADMINISTRATEUR , {
foreignKey: {
allowNull: false
}
});
models.PRODUCTEURS.hasMany(models.CLIENTS);
models.PRODUCTEURS.hasMany(models.PRODUITS);
models.PRODUCTEURS.hasMany(models.ADRESSE_CLIENTS);
models.PRODUCTEURS.hasMany(models.CATEGORY_PRODUITS);
models.PRODUCTEURS.hasMany(models.COMMANDES);
} }; PRODUCTEURS.init({
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
avatar: DataTypes.STRING }, {
sequelize,
modelName: 'PRODUCTEURS', }); return PRODUCTEURS; };
I finally found the answer I had to put the variable "const {UniqueConstraintError} = require ('sequelize / types')" in comment and retype sequelize db: migrate

ERROR: Cannot add foreign key constraint-

I wrote a nodejs app with mysql db and Sequalize as an ORM. Every things is ok. I define models and migration to create database and seeders. I want to create a product model that in this model i have two foreign keys: (categoryId & shopId).
when i was create migration files, I create shop model after product model. and this is create a problem for me. when i want to create table in database using "sequelize db:migrate" command i get this error:
ERROR: Cannot add foreign key constraint
I read this link and know this is not the reason for my problem.
but how can i resolve this bug? i try to define up and down as an async function but this error did not resolve.
module.exports = {
up: (queryInterface, Sequelize) => queryInterface.createTable(
'products', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
name: {
type: Sequelize.STRING(255),
allowNull: false,
},
description: {
type: Sequelize.STRING(1024),
allowNull: false,
},
price: {
type: Sequelize.FLOAT,
allowNull: false,
},
old_price: {
type: Sequelize.FLOAT,
allowNull: false,
},
type: {
type: Sequelize.STRING(255),
},
height: {
type: Sequelize.INTEGER,
},
width: {
type: Sequelize.INTEGER,
},
categoryId: {
type: Sequelize.INTEGER,
references: {
model: 'categories',
key: 'id',
},
},
shopId: {
type: Sequelize.INTEGER,
references: {
model: 'shops',
key: 'id',
},
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
},
),
down: (queryInterface, Sequelize) => queryInterface.dropTable('products'),
}
You're passing the model as string. You need to point to your class.
Try this:
categoryId: {
type: Sequelize.INTEGER,
references: {
model: categories,
key: 'id',
},
},

sequelize many to many not working correcttly with a legacy databse

I've got an existing mysql database where i've got the following tables : category,product and product_category.I've used sequelizer-auto package to generate models from the 3 tables like the following:
Product.js ,model generated from product table:
module.exports = function(sequelize, DataTypes) {
const Product= sequelize.define('product', {
productId: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'product_id'
},
name: {
type: DataTypes.STRING(100),
allowNull: false,
field: 'name'
},
description: {
type: DataTypes.STRING(1000),
allowNull: false,
field: 'description'
},
price: {
type: DataTypes.DECIMAL,
allowNull: false,
field: 'price'
},
discountedPrice: {
type: DataTypes.DECIMAL,
allowNull: false,
defaultValue: '0.00',
field: 'discounted_price'
},
image: {
type: DataTypes.STRING(150),
allowNull: true,
field: 'image'
},
image2: {
type: DataTypes.STRING(150),
allowNull: true,
field: 'image_2'
},
thumbnail: {
type: DataTypes.STRING(150),
allowNull: true,
field: 'thumbnail'
},
display: {
type: DataTypes.INTEGER(6),
allowNull: false,
defaultValue: '0',
field: 'display'
}
}, {
tableName: 'product'
});
Product.associate=(models)=>{
Product.belongsToMany(models.category,{
through:'product_category',
foreignkey:'product_id',
as:'categories'
})
}
return Product;
};
Category.js generated from 'category table'
module.exports = function(sequelize, DataTypes) {
const Category= sequelize.define('category', {
categoryId: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'category_id'
},
departmentId: {
type: DataTypes.INTEGER(11),
allowNull: false,
field: 'department_id'
},
name: {
type: DataTypes.STRING(100),
allowNull: false,
field: 'name'
},
description: {
type: DataTypes.STRING(1000),
allowNull: true,
field: 'description'
}
},
{
tableName: 'category',
});
Category.associate=(models)=>{
Category.belongsToMany(models.Product, {
through: 'product_category',
foreignkey: 'category_id',
as: 'products'
});
}
return Category;
};
ProductCategory from product_category table
module.exports = function(sequelize, DataTypes) {
return sequelize.define('product_category', {
productId: {
type: DataTypes.INTEGER(11),
references:{
key:'product_id',
model:'product'
}
},
categoryId: {
type: DataTypes.INTEGER(11),
references:{
key: 'category_id',
model:'category'
}
}
}, {
tableName: 'product_category'
});
};
And here is the category controller categories.js:
const db=require('../services/db_init');
const DataTypes=require('sequelize').DataTypes;
const Category=require('../database/models/Category')(db,DataTypes);
const Product=require('../database/models/Product')(db,DataTypes);
const {category_errors:{cat_01,cat_02}} = require('../services/errors.js');
//test code
const Product = require('../database/models/Product')(db,DataTypes);
module.exports=(app)=>{
app.get('/categories',async(req,res)=>{
try {
const categories = await Category.findAll({
include:{
model:Product,
as:'products'
}
});
return res.send(categories).status(200);
} catch (err) {
return res.json({error:err}).status(400);
}
});
app.get('/categories/:id',async(req,res)=>{
const id=req.params.id;
//checking if the id is a number
if(isNaN(id)){
return res.json({error:cat_01})//error returned
}
try {
const category=await Category.findByPk(id);
if(category){
return res.send(category).status(200);
}
return res.json({error:cat_02}).status(404);
} catch (err) {
return res.json(err).status(400);
}
});
}
All methode are working as expected,but after adding relashionship between models i've got some problems.First in GET /categories ,the implementation of the query was const categories = await Category.findAll() and everything was working fine,but after changing the implementation to const categories = await Category.findAll({include:{model:Product,as:'products'}}); i get the follwing error {
"error": {
"name": "SequelizeEagerLoadingError"
}
}
I've tried to read many topics,and solutions but i always have the same issue

sequelize error: missing index for constraint

20181005120552-create-order-detail.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('OrderDetails', {
orderDetailId: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true,
},
orderId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Orders',
key: 'orderId'
}
},
productName: {
type: Sequelize.STRING,
primaryKey: true,
allowNull: false,
},
count: {
type: Sequelize.INTEGER
},
orderDetailPrice: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Orders',
key: 'totalPrice'
}
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('OrderDetails');
}
};
20181005120522-create-order
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface
.createTable('Orders', {
orderId: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
userId: {
type: Sequelize.STRING,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'userId'
}
},
orderDate: {
type: Sequelize.DATE
},
totalPrice: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
},
orderState: {
type: Sequelize.STRING
},
shippingNumber: {
type: Sequelize.STRING
},
basicAddress: {
type: Sequelize.STRING
},
detailAddress: {
type: Sequelize.STRING
},
telNumber: {
type: Sequelize.INTEGER
},
phoneNumber: {
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Orders');
}
};
When i executed script sequelize db:migrate, previous migration is without errors executed. in this level it returns error. I don't know how can i resolve this problem i guess it has something wrong.
ERROR: Failed to add the foreign key
constraint. Missing index for
constraint 'orderdetails_ibfk_2' in
the referenced table 'orders'
This is error message. I wanna connect files OrderDetails.orderDetailPrice and Orders.totalPrice.
Thanks.
As reported here, it seems that Sequelize has some issues with references to composite keys.
However, by exploiting the Sequelize query execution you can workaround you problem. In you case you can perform the following mysql query:
ALTER TABLE `db_test`.`OrderDetails` ADD CONSTRAINT `fk_order_detailes_orders`
FOREIGN KEY (`orderId` , `orderDetailId`)
REFERENCES `db_test `.`orders`(`orderId` , `totalPrice`);
So your create-order-detail migration file becomes the following:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('OrderDetails', {
orderDetailId: {
type: Sequelize.INTEGER.UNSIGNED,
primaryKey: true,
allowNull: false,
autoIncrement: true,
},
orderId: {
type: Sequelize.INTEGER,
allowNull: false,
},
productName: {
type: Sequelize.STRING,
primaryKey: true,
allowNull: false,
},
count: {
type: Sequelize.INTEGER,
},
orderDetailPrice: {
type: Sequelize.INTEGER,
allowNull: false,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
})
.then(() => {
return queryInterface.sequelize.query('ALTER TABLE `OrderDetails` ADD ' +
'CONSTRAINT `fk_order_details_orders` FOREIGN KEY (`orderId`, `orderDetailPrice`) REFERENCES ' +
'Orders(`orderId`, `totalPrice`)');
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('OrderDetails', null);
},
};
Giordano,
I defined this way the code is below. Let me know why this code can be migrated? primary key and unique key both keys are written though..
create-order-detail.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('OrderDetails', {
(...),
productName: {
type: Sequelize.STRING,
primaryKey: true,
// allowNull: false
unique: true
},
count: {
type: Sequelize.INTEGER
},
orderDetailPrice: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
// references: {
// model: 'Orders',
// key: 'totalPrice'
// }
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
.then(() => {
queryInterface.addConstraint('OrderDetails', ['orderDetailPrice'], {
type: 'foreign key',
references: {
name: 'orderdetails_ibfk_2',
table: 'Orders',
field: 'totalPrice'
},
})
})
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('OrderDetails');
}
};