Trying to generate a migration after generating the models using sequelize-auto - mysql

I have run this command to generate the models from my MySQL:
node node_modules/sequelize-auto/bin/sequelize-auto -h localhost -d coasteye_new -u root -x PASSWORD --dialect mysql -o models
So the models are now stored in the "node_project/models" directory. For example this one:
const Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
id: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
name: {
type: DataTypes.STRING(100),
allowNull: true,
unique: "name"
},
password: {
type: DataTypes.STRING(100),
allowNull: false
},
id_role: {
type: DataTypes.INTEGER,
allowNull: false
},
role: {
type: DataTypes.ENUM('root','twm staff','client'),
allowNull: false
},
email: {
type: DataTypes.STRING(70),
allowNull: false,
unique: "unique_email"
},
fullname: {
type: DataTypes.STRING(100),
allowNull: true
},
activated: {
type: DataTypes.TINYINT,
allowNull: false,
defaultValue: 1
},
token: {
type: DataTypes.STRING(100),
allowNull: false
},
phone: {
type: DataTypes.STRING(70),
allowNull: false
},
api_token: {
type: DataTypes.STRING(200),
allowNull: true
},
api_token_valid_until: {
type: DataTypes.DATE,
allowNull: true
},
has_stations_in_the_new_user_deployment_xref_table: {
type: DataTypes.TINYINT,
allowNull: false,
defaultValue: 0
},
send_the_status_daily_report_by_email: {
type: DataTypes.TINYINT,
allowNull: false,
defaultValue: 0
}
}, {
sequelize,
tableName: 'user',
timestamps: false,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "id" },
]
},
{
name: "unique_email",
unique: true,
using: "BTREE",
fields: [
{ name: "email" },
]
},
{
name: "name",
unique: true,
using: "BTREE",
fields: [
{ name: "name" },
]
},
]
});
};
After that I have modified the field "phone" by "telephone" this way:
phone: {
type: DataTypes.STRING(70),
allowNull: false
},
to
telephone: {
type: DataTypes.STRING(70),
allowNull: false
},
Then I have run this:
(env) jgarcia#Javier-PC:/var/www/node_test$ npx sequelize
migration:generate --name test_migration
Sequelize CLI [Node: 18.3.0, CLI: 6.4.1, ORM: 6.20.1]
migrations folder at "/var/www/node_test/migrations" already exists.
New migration was created at
/var/www/node_test/migrations/20220615115322-test_migration.js .
But I get an "empty" migration as you can see here below:
(env) jgarcia#Javier-PC:/var/www/node_test$ cat /var/www/node_test/migrations/20220615115322-test_migration.js
'use strict';
module.exports = {
async up (queryInterface, Sequelize) {
/**
* Add altering commands here.
*
* Example:
* await queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
},
async down (queryInterface, Sequelize) {
/**
* Add reverting commands here.
*
* Example:
* await queryInterface.dropTable('users');
*/
}
};
I expected that the file 20220615115322-test_migration.js contained some reference to my change: from phone to telephone.
Regards
Javier

This is what the migration:generate CLI command does. It doesn't interact with your models at all. See this SO thread for additional information.
You can pass additional parameters into your migration:generate command to get the CLI to write some of the code for you. You can also use Sequelize Auto-Migrations, but that package has not seen any updates in a long time and probably has compatibility issues with newer versions of Sequelize.

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));
}
},

Sequelize Eager Loading Error: social_logins not associated to users

Users Model defined like this.
const db = require ('../../config/db_config');
const users = db.sequelize.define('users', {
id: {
type: db.DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
first_name: {
type: db.DataTypes.STRING(150),
},
last_name: {
type: db.DataTypes.STRING(150),
},
email: {
type: db.DataTypes.STRING(256),
required: true,
unique: true
},
password: {
type: db.DataTypes.STRING,
},
student_id: {
type: db.DataTypes.STRING
},
status: {
type: db.DataTypes.BOOLEAN,
required: true,
defaultValue: 0
},
is_deleted: {
type: db.DataTypes.BOOLEAN,
required: true,
defaultValue: 0
},
createdAt: db.DataTypes.DATE,
updatedAt: db.DataTypes.DATE,
});
module.exports = users;
social_logins Model defined like this
const db = require ('../../config/db_config');
const socialLogins = db.sequelize.define('social_logins', {
id: {
type: db.DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
token: {
type: db.DataTypes.STRING
},
tokenType: {
type: db.DataTypes.STRING
},
fb_id: {
type: db.DataTypes.STRING
},
user_id: {
type: db.DataTypes.INTEGER
},
is_deleted: {
type: db.DataTypes.BOOLEAN,
required: true,
defaultValue: false
}
}, { underscored: true, timestamp: true, tableName: 'social_logins' });
module.exports = socialLogins;
User model associated with the social_logins model using belongsTo function
socialLoginsModel.belongsTo(users)
Sequelize throws eagerLoadingError
Error EagerLoadingError [SequelizeEagerLoadingError]: social_logins is
not associated to users!
While running this query given below.
const userModel = require ('./users_model');
const socialLoginModel = require('../social_logins/social_logins_model');
let id = "123456";
let email = "ex#example.com";
userModel.findOne({
where: { email },
include: [{
model: socialLogins,
where: {
fb_id: id
}
}]
});
you should have associations like this based on your model names
socialLogins.belongsTo(users) & users.hasOne(socialLogins)/ users.hasMany(socialLogins) based on your relations being defined in DB

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',
},
},

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.

why model not fetching all attributes in table in sequelize

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