I've two models, User and Category
User model:
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.BIGINT(19),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
firstname: {
type: DataTypes.STRING(150),
allowNull: false
},
lastname: {
type: DataTypes.STRING(150),
allowNull: false
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING(255),
allowNull: false
}
}, {
tableName: 'users',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
defaultScope: {
attributes: {
exclude: ['password']
}
},
scopes: {
withPassword: {
attributes: {}
}
}
})
User.prototype.toJSON = function () {
let values = Object.assign({}, this.get())
delete values.password
return values
}
return User
}
Category model:
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
id: {
type: DataTypes.BIGINT(19),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING(150),
allowNull: false
},
created_by: {
type: DataTypes.BIGINT(19),
allowNull: false,
references: {
model: 'users',
key: 'id'
}
}
}, {
tableName: 'categories',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at'
})
Category.associate = (models) => {
Category.belongsTo(models.User, {
foreignKey: 'created_by'
})
}
return Category
}
My query to find the category:
const category = await Category.findOne({
include: [{
model: User,
required: true,
attributes: ['id', 'firstname', 'lastname', 'email']
}],
where: {
id: req.params.id
},
limit: 1
})
When I execute the query, the response I expected was,
{
"id": 1,
"name": "License",
"created_by": {
"id": 1,
"firstname": "Magesh",
"lastname": "Kumaar",
"email": "mk#test.com"
},
"created_at": "2018-09-03T07:41:29.000Z",
"updated_at": "2018-09-03T07:41:29.000Z"
}
But the response I obtained was,
{
"id": 1,
"name": "License",
"created_by": 1, // I expected the user information here
"created_at": "2018-09-03T07:41:29.000Z",
"updated_at": "2018-09-03T07:41:29.000Z",
"User": {
"id": 1,
"firstname": "Magesh",
"lastname": "Kumaar",
"email": "mk#test.com"
}
}
The user information is available at both created_by as Id and another User property that contains other information
I tried the as option, but it didn't seem to work. Is there any way to get the user information in the created_by key itself.
Need use aliases.
http://docs.sequelizejs.com/manual/tutorial/associations.html
Example:
index.js
require('dotenv').load();
const { User, Category } = require('./models');
const sequelize = require('./database');
(async () => {
await sequelize.sync({ force: true });
await Category.associate({ User });
await User.create({
firstname: 'firstname',
lastname: 'lastname',
email: 'email#email.email',
password: 'password',
});
await Category.create({
name: 'name',
created_by: '1',
});
const category = await Category.findOne({
attributes: ['id'],
include: {
model: User,
required: true,
as: 'created',
attributes: ['id', 'firstname', 'lastname', 'email']
},
where: {
id: 1,
},
});
console.log(category.toJSON());
})();
Category Model file:
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
id: {
type: DataTypes.BIGINT(19),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING(150),
allowNull: false
},
created_by: {
type: DataTypes.BIGINT(19),
allowNull: false,
references: {
model: 'users',
key: 'id'
}
}
}, {
tableName: 'categories',
timestamps: true,
createdAt: false,
updatedAt: false,
});
Category.associate = (models) => {
Category.belongsTo(models.User, {
foreignKey: 'created_by',
as: 'created',
})
};
return Category;
};
result:
{ id: 1,
created:
{ id: 1,
firstname: 'firstname',
lastname: 'lastname',
email: 'email#email.email' } }
Related
I am trying to write a join query using belongsTo but getting error:
Error: LearningCertificateEvent.belongsTo called with something that's
not a subclass of Sequelize.Model
at Function. (/Users/msmexmac/node/msmex-backend/msmex-api/node_modules/sequelize/lib/associations/mixin.js:93:13)
I am trying to fetch events related to learning cerfificate events. I tried every thing but it does not work somehow.
My models are as follows:
LearningCertificate Model
"use strict";
const Sequelize = require("sequelize");
const sequelize = require("../helpers/db");
const LearningCertificateEvent = require("./LearningCertificateEvent");
const LearningCertificate = sequelize.define(
"LearningCertificate",
{
id: {
autoIncrement: true,
type: Sequelize.BIGINT,
primaryKey: true,
},
userId: {
type: Sequelize.INTEGER,
field: "user_id",
},
certificateURL: {
type: Sequelize.STRING,
field: "certificate_url",
},
certificatePNGURL: {
type: Sequelize.STRING,
field: "certificate_png_url",
},
certificateType: {
type: Sequelize.STRING,
field: "certificate_type",
},
createdAt: {
type: Sequelize.BIGINT,
field: "created_at",
},
updatedAt: {
type: Sequelize.BIGINT,
field: "updated_at",
},
},
{
timestamps: false,
tableName: "learning_certificate",
}
);
LearningCertificate.hasMany(LearningCertificateEvent, {
foreignKey: "certificateId",
});
module.exports = LearningCertificate;
The second model is : LearningCertificateEvent Model
"use strict";
const Sequelize = require("sequelize");
const sequelize = require("../helpers/db");
const MsmexEvent = require("./MsmexEvent");
const LearningCertificateEvent = sequelize.define(
"LearningCertificateEvent",
{
id: {
autoIncrement: true,
type: Sequelize.BIGINT,
primaryKey: true,
},
userId: {
type: Sequelize.INTEGER,
field: "user_id",
},
certificateId: {
type: Sequelize.INTEGER,
field: "certificate_id",
},
eventId: {
type: Sequelize.INTEGER,
field: "event_id",
},
createdAt: {
type: Sequelize.BIGINT,
field: "created_at",
},
updatedAt: {
type: Sequelize.BIGINT,
field: "updated_at",
},
},
{
timestamps: false,
tableName: "learning_certificate_event",
}
);
LearningCertificateEvent.belongsTo(MsmexEvent, {
foreignKey: "eventId",
});
// MsmexEvent.hasMany(LearningCertificateEvent, {
// foreignKey: "eventId",
// });
module.exports = LearningCertificateEvent;
And last model is: MsmexEvent Model
"use strict";
const Sequelize = require("sequelize");
const sequelize = require("../helpers/db");
const LearningCertificateEvent = require("./LearningCertificateEvent");
const Event = sequelize.define(
"Event",
{
id: {
autoIncrement: true,
type: Sequelize.BIGINT,
primaryKey: true,
},
identifier: {
type: Sequelize.STRING,
field: "identifier",
},
expertId: {
type: Sequelize.INTEGER,
field: "expert_id",
},
waitList: {
type: Sequelize.BOOLEAN,
field: "waitList",
},
},
{
timestamps: false,
tableName: "msmex_event",
}
);
module.exports = Event;
The query which I have written is as follows:
return LearningCertificate.findAll({
where: {
userId: userId,
},
include: [
{
model: LearningCertificateEvent,
required: true,
include: [
{
model: MsmexEvent,
required: true,
},
],
},
],
order: [["id", "DESC"]],
});
In query however if I replace MsmexEvent with some other table for example User it works fine.
Can some one please help ?
There are 2 tables which are users and tutorial.
The relationship:
users(1) : tutorial(Many)
The users table has below column
completeOneOfTheTutorial: {
type: DataTypes.BOOLEAN,
allowNull: false,
...
},
which is true when
isCompleted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is true in one of the tutorials.
If isCompleted is false for all tutorials of the same user, completeOneOfTheTutorial will be false
Example
User table
[
{
id: "user1",
completeOneOfTheTutorial: true
}
,
{
id: "user2",
completeOneOfTheTutorial: false
},
]
tutorial table
[
{
id: "tutorial1",
userId: "user1",
isCompleted: true
}
,
{
id: "tutorial2",
userId: "user1",
isCompleted: false
},
{
id: "tutorial1",
userId: "user2",
isCompleted: false
}
,
{
id: "tutorial2",
userId: "user2",
isCompleted: false
},
]
How should I modify this field in users.model.js
completeOneOfTheTutorial: {
type: DataTypes.BOOLEAN,
allowNull: false,
...
},
users.model.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const users = sequelizeClient.define('users', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4,
},
completeOneOfTheTutorial: {
type: DataTypes.BOOLEAN,
allowNull: false,
...
},
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
users.associate = function (models) {
users.hasMany(models.tutorial,{
foreignKey: 'userId'
});
};
return users;
};
tutorial.model.js
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const tutorial = sequelizeClient.define('tutorial', {
id: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4
},
isCompleted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
tutorial.associate = function (models) {
tutorial.belongsTo(models.users);
};
return tutorial;
};
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
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
I have 4 models: User, Skill, SkillToLearn, and SkillToTeach. The SkillToLearn and SkillToTeach contain two columns userId and skillId to keep track of a skill (given by skillId) that a user (given by userId) wants to learn or teach.
My goal is to use Sequelize's include statement such that I can return all users' data, including a list of skills they are learning and a list of skills they are teaching. I want a response similar to the following:
[
{
"id": 1,
"username": "janedoe",
"skillsLearning": [
{
"skillId": 1,
"name": "arts"
}
],
"skillsTeaching": [
{
"skillId": 2,
"name": "cooking"
}
]
}
]
However, instead, I'm getting the following response:
[
{
"id": 1,
"username": "janedoe",
"skillsLearning": [
{
"skillId": 1,
"Skill": {
"name": "arts"
}
}
],
"skillsTeaching": [
{
"skillId": 2,
"Skill": {
"name": "cooking"
}
}
]
}
]
I have tried to include Skill instead of SkillToLearn and SkillToTeach but I got an error saying that Skill is not associated to User. I am uncertain if my schemas and associations are incorrect.
User.js
const User = sequelize.define("User", {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT
}
}, {
freezeTableName: true
});
User.associate = function (models) {
User.hasMany(models.SkillToLearn, {
as: "skillsLearning",
onDelete: "cascade",
foreignKey: "userId",
sourceKey: "id"
});
User.hasMany(models.SkillToTeach, {
as: "skillsTeaching",
onDelete: "cascade",
foreignKey: "userId",
sourceKey: "id"
});
};
Skill.js
const Skill = sequelize.define("Skill", {
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true
}
}, {
freezeTableName: true
});
Skill.associate = function (models) {
Skill.hasMany(models.SkillToLearn, {
as: "usersLearning",
onDelete: "cascade",
foreignKey: "skillId",
sourceKey: "id"
});
Skill.hasMany(models.SkillToTeach, {
as: "usersTeaching",
onDelete: "cascade",
foreignKey: "skillId",
sourceKey: "id"
});
};
SkillToLearn.js
const SkillToLearn = sequelize.define("SkillToLearn", {
userId: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
skillId: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
}
}, {
freezeTableName: true
});
SkillToLearn.associate = function (models) {
SkillToLearn.belongsTo(models.User, {
foreignKey: "userId",
targetKey: "id"
});
SkillToLearn.belongsTo(models.Skill, {
foreignKey: "skillId",
targetKey: "id"
});
};
SkillToTeach.js
const SkillToTeach = sequelize.define("SkillToTeach", {
userId: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
skillId: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
}
}, {
freezeTableName: true
});
SkillToTeach.associate = function (models) {
SkillToTeach.belongsTo(models.User, {
foreignKey: "userId",
targetKey: "id"
});
SkillToTeach.belongsTo(models.Skill, {
foreignKey: "skillId",
targetKey: "id"
});
};
dataRoutes.js
db.User
.findAll({
attributes: ["id", "username"],
include: [
{
model: db.SkillToLearn,
as: "skillsLearning",
attributes: ["skillId"],
include: [
{
model: db.Skill,
attributes: ["name"]
}
]
},
{
model: db.SkillToTeach,
as: "skillsTeaching",
attributes: ["skillId"],
include: [
{
model: db.Skill,
attributes: ["name"]
}
]
}
]
})
.then(results => res.json(results));
});
Is there a way for me to get the skill's name without having it in an object? Should I just do multiple queries and construct the response using my own object literal? Thank you!