ERROR: Cannot find module 'sequelize/types' - mysql

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

Related

Cannot find module 'sequelize/types'

anyone knows why i am getting this error
this is my code
"use strict";
const { DataTypes } = require("sequelize/types");
module.exports = {
up: async (queryInterface, DataTypes) => {
await queryInterface.createTable("dummytables", {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
id: {
type: DataTypes.NUMBER,
},
first_name: {
type: DataTypes.STRING,
allowNull: false,
},
last_name: {
type: DataTypes.STRING,
allowNull: false,
},
});
},
down: async (queryInterface, DataTypes) => {
await queryInterface.dropTable("dummytables");
},
};
when am trying to run this command sequelize db:migrate
and its showing me ERROR: Cannot find module 'sequelize/types'
my dependencies file
"dependencies": {
"#types/sequelize": "^4.28.9",
"express": "^4.17.1",
"mysql2": "^2.2.5",
"sequelize": "^6.5.0",
"sequelize-cli": "^6.2.0" }
any solution need help
"use strict";
//const { DataTypes } = require("sequelize/types"); // Remove this line
module.exports = {
up: async (queryInterface, DataTypes) => {
await queryInterface.createTable("dummytables", {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
id: {
type: DataTypes.NUMBER,
},
first_name: {
type: DataTypes.STRING,
allowNull: false,
},
last_name: {
type: DataTypes.STRING,
allowNull: false,
},
});
},
down: async (queryInterface, DataTypes) => {
await queryInterface.dropTable("dummytables");
},
};
If you change the second line to;
const { DataTypes } = require("sequelize");
It should work fine.
A better fix would be to just install Sequelize like;
const Sequelize = require("sequelize");
then use it like;
first_name: {
type: Sequelize.STRING,
allowNull: false,
},
You might not even need to do the importation because up() would give it to you for free, You just need to replace DataTypes with Sequelize.
async up(queryInterface, Sequelize) {
...
}
This error, may be can happen when you use auto import and it import sequelize/types, you can find in code has 'sequelize/types' and delete it in code of you should change
const {DataTypes} = require('sequelize');

Sequelize - ORM - Associations not working

Using Sequelize with MySQL. I have three models. Consultant, FamilyMember and Appointments. Appointment refers to Consultant and FamilyMember.
I have defined the foreign keys in the Appointment model. When the DB is created - the foreign keys are visible - when I check through a MySQL client, on the appointment table. The table names are freeze - so there isn't any chance of pluralization of the table names.
Consultant Model:
module.exports = (sequelize, DataTypes) => {
const consultant = sequelize.define('consultant', {
ID: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false
},
FirstName: {
type: DataTypes.STRING,
allowNull: false
},
LastName: {
type: DataTypes.STRING,
allowNull: false
}
{
freezeTableName: true
}
);
return consultant;
};
Appointment Model:
module.exports = (sequelize, DataTypes) => {
const appointment = sequelize.define('appointment', {
// attributes
ID: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false
},
ConsultantID: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'consultant',
key: 'ID'
}
},
FamilyMemberID: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'familymember',
key: 'ID'
}
}
},
{
freezeTableName: true
}
);
appointment.associate = function (models) {
models.appointment.belongsTo(models.consultant, {
foreignKey: 'ConsultantID',
as: 'consultant',
});
models.appointment.belongsTo(models.familymember, {
foreignKey: 'FamilyMemberID',
as: 'familymember',
});
};
return appointment;
};
Family Member model:
module.exports = (sequelize, DataTypes) => {
const familymember = sequelize.define('familymember', {
// attributes
ID: {
primaryKey: true,
type: DataTypes.UUID,
allowNull: false
},
FamilyID: {
type: DataTypes.UUID,
allowNull: false
},
FirstName: {
type: DataTypes.STRING,
allowNull: false
},
LastName: {
type: DataTypes.STRING,
allowNull: false
}
},
{
freezeTableName: true
}
);
return familymember;
};
Then in the code I try to fetch appointment and get the related familymember and consultant like this
var appointments = await Appointment.findAll({
where: {
AppointmentDateConfirmed: {
$gte: moment().subtract(0, 'days').toDate()
}
}, include:[Consultant, FamilyMember]
}
)
However I get an error
UnhandledPromiseRejectionWarning: SequelizeEagerLoadingError: consultant is not associated to appointment!
I suppose you should register your associations after models registration like I pointed in this answer

SequelizeEagerLoadingError: product is not associated to collection

I use sequelize ORM in Mysql. I have 3 Models: Product, Collection, CollectionProduct
relationship between Product and Collection are many to many and for handle this in sequelize i used belongsToMany association. every thing is Ok but when i run this code to get a collection with its products with include Eager this error occure:
SequelizeEagerLoadingError: product is not associated to collection!
Product Model:
module.exports = (sequelize, Sequelize) => {
const Product = sequelize.define('product', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
name_en: {
type: Sequelize.STRING(255),
},
description_en: {
type: Sequelize.STRING(1024),
},
price: {
type: Sequelize.FLOAT,
allowNull: false,
},
type: {
type: Sequelize.STRING(255),
},
height: {
type: Sequelize.INTEGER,
},
width: {
type: Sequelize.INTEGER,
},
createdAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
allowNull: false,
},
updatedAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
allowNull: false,
},
}, {})
Product.associate = (models) => {
Product.belongsToMany(models.collection, { through: models.collectionProduct, as: 'collections', foreignKey: 'productId' })
}
return Product
}
Collection Model :
module.exports = (sequelize, Sequelize) => {
const Collection = sequelize.define(
'collection', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true,
},
name_en: {
type: Sequelize.STRING(255),
},
itemsCount: {
type: Sequelize.INTEGER,
},
createdAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
allowNull: false,
},
updatedAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
allowNull: false,
},
}, {},
)
Collection.associate = (models) => {
Collection.belongsToMany(models.product, { through: models.collectionProduct, as: 'products', foreignKey: 'collectionId' })
}
return Collection
}
CollectionProduct Model:
module.exports = (sequelize, Sequelize) => {
const CollectionProduct = sequelize.define('collectionProduct', {
collectionId: {
type: Sequelize.INTEGER,
},
productId: {
type: Sequelize.INTEGER,
},
createdAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
allowNull: false,
},
updatedAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW,
allowNull: false,
},
}, {})
CollectionProduct.associate = (models) => {}
return CollectionProduct
}
routes/collection.js
const express = require('express')
const router = express.Router()
const Collection = require('../../controllers/collectionController')
router.get('/:id', async (req, res) => {
const { id: collectionId } = req.params
const collection = await Collection.getOne(collectionId)
return collection
}
collectionController
const db = require('../models/index')
const Collection = db.collection
const Product = db.product
const getOne = async (collectionId) => {
const collection = await Collection.findByPk(collectionId, {
include: {
model: Product,
as: 'products',
attributes: ['id', 'name_en'],
},
})
return collection
}
I found my problem. in collectionController i used model: Product
and Product should be a sequelize model. but in my code this is a function that have been called in models/index. so i changed my calling and pass a sequelize model to getOne

Sequelize hasMany is working fine but the inverse relation is not working

I am trying to work with mysql relations in Node Js(express Js) using Sequelize.
User.hasMany(Post); work just fine, but when i try to inverse it in Post model like: Post.belongsTo(User);
got this error:
throw new Error(${source.name}.${_.lowerFirst(Type.name)} called with something that's not a subclass of Sequelize.Model);
Error: post.belongsTo called with something that's not a subclass of Sequelize.Model
User model like:
const Sequelize = require('sequelize');
const db = require('../config/db');
const Post = require('./Post');
const User = db.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
notNull: true,
primaryKey: true
},
name: {
type: Sequelize.STRING,
notNull: true
},
email: {
type: Sequelize.STRING,
notNull: true
},
password: {
type: Sequelize.STRING,
notNull: true
}
});
User.hasMany(Post);
module.exports = User;
And Post model like:
const Sequelize = require('sequelize');
const db = require('../config/db');
const User = require('./User');
const Post = db.define('post', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
notNull: true,
primaryKey: true
},
title: {
type: Sequelize.STRING,
notNull: true
},
description: {
type: Sequelize.TEXT,
notNull: true
},
author: {
type: Sequelize.STRING,
notNull: true
}
});
Post.belongsTo(User);
module.exports = Post;
How can i solve this problem?
Thanks everyone...
You should correct your model definition exports as functions and define associate function in each model definition function like this and call it all after all models are registered in some module like database.js:
user.js
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
notNull: true,
primaryKey: true
},
...
User.associate = function (models) {
User.hasMany(models.Post)
}
post.js
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('post', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
notNull: true,
primaryKey: true
},
...
Post.associate = function (models) {
Post.belongsTo(models.User)
}

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