How create (optimize) service on Backend (ExpressJS) with sequelize - javascript

Tried to create API for internet store using ExpressJS and sequelize. I have users, basket and devices. To connect basket and choosen by user devices used middle table BasketDevice.
Models:
export const Models = {
User: sequelize.define('user',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
email: { type: DataTypes.STRING, unique: true },
password: { type: DataTypes.STRING },
role: { type: DataTypes.STRING, defaultValue: 'USER' },
isActivated: { type: DataTypes.BOOLEAN, defaultValue: false},
activationLink: { type: DataTypes.STRING, unique: true }
}
),
Basket: sequelize.define('basket',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
}
),
BasketDevice: sequelize.define('basketDevice',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
}
),
Device: sequelize.define('device',
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, allowNull: false, unique: true },
price: { type: DataTypes.INTEGER, allowNull: false },
img: { type: DataTypes.STRING, allowNull: false },
rating: { type: DataTypes.INTEGER, defaultValue: 0 },
}
}
Assotiations between tables:
Models.User.hasOne(Models.Basket)
Models.Basket.belongsTo(Models.User)
Models.Basket.hasMany(Models.BasketDevice, {as: 'devices'})
Models.BasketDevice.belongsTo(Models.Basket)
Models.Device.hasMany(Models.BasketDevice)
Models.BasketDevice.belongsTo(Models.Device)
Tryed to give in response basket include basket device
Basket service:
class BasketService {
async getBasket(token: string) {
const userData = await TokenService.verifyRefreshToken(token) as any
const basket = await Models.Basket.findOne({
where: { userId: userData.id },
include: [{model: Models.BasketDevice, as: 'devices'}]
})
return basket
}
}
Don't know how create getBasket function that gives added to cart devices and counting of one device
What is the opltimal way to give devices added in basket?

Related

foreignKey seems not working in a belongsTo clause

PROBLEM
I'm using sequelize to make an auto-generated query with a JOIN and I get that :
SELECT [...] FROM `weapon` AS `weapon` LEFT OUTER JOIN `stat` AS `mainStat` ON `weapon`.`ID` = `mainStat`.`ID` WHERE `weapon`.`type` = 'polearm';
However, the ON clause is incorrect, in fact, I want that :
[...] ON `weapon`.`mainStatID` = `mainStat`.`ID` [...]
Here is the associations I declared :
Weapon.hasOne( Stat, { foreignKey: 'mainStatID', as: 'mainStat' });
Stat.belongsTo( Weapon );
Stat.belongsTo( Weapon ); Just don't change anything.
Maybe I didn't understand something with .hasOne() and .belongsTo() concept ?
MODELS
Here is the two concerned Models :
const Weapon = sequelize.define('weapon', {
ID : { type: DataTypes.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true },
name : { type: DataTypes.STRING, allowNull: false },
shortName : { type: DataTypes.STRING, allowNull: false },
type : { type: DataTypes.STRING, allowNull: false },
rarity : { type: DataTypes.INTEGER, allowNull: false },
baseAtk : { type: DataTypes.INTEGER, allowNull: false },
mainStatID : { type: DataTypes.INTEGER, allowNull: false },
description : { type: DataTypes.STRING, allowNull: false },
maxStack : { type: DataTypes.BOOLEAN, allowNull: false },
optionalEffect: { type: DataTypes.STRING, allowNull: true }
},
{
freezeTableName: true,
timestamps: false
})
const Stat = sequelize.define('stat', {
ID : { type: DataTypes.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true },
displayName: { type: DataTypes.STRING, allowNull: false },
shortName : { type: DataTypes.STRING, allowNull: false },
value : { type: DataTypes.FLOAT, allowNull: false, get() {return parseFloat(this.getDataValue('value'))} }
},
{
freezeTableName: true,
timestamps: false
})
*Using mysql and sequelize 6.25.4
First of all, you should remove the explicit field definition for the foreign key:
mainStatID: { type: DataTypes.INTEGER, allowNull: false },
Secondly, if you would like a foreign-key field of MainStatID in the Weapon table then the relationship should be:
Weapon.belongsTo(Stat, { as: 'MainStat' });

Nodejs Sequelize belongsToMany not working

I dont know why I am getting this error error: SequelizeDatabaseError: Unknown column 'student-> section ->grademapping.studentId' in 'field list' I just follow this documentation on how to use belongsToMany did i miss something on the documentation? https://sebhastian.com/sequelize-belongstomany/
let student = await Database.getConnection().models.Student;
let grademapping = await Database.getConnection().models.Grademapping;
let section = await Database.getConnection().models.Section;
let taxtypemapping = await student.findAll({
attributes:['_id','FirstName','LastName', 'section.Description'],
include:[
{ model: section, attribute:[] }
],
raw: true
})
the models
class taxtypedetails extends Sequelize.Model {}
Section.init(
{
_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
Description: {
type: Sequelize.STRING,
},
},
{ sequelize, tableName: 'section', timestamps: false },
)
class Student extends Sequelize.Model {}
Student.init(
{
_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
FirstName: {
type: Sequelize.STRING,
},
LastName: {
type: Sequelize.STRING,
},
},
{ sequelize, tableName: 'student', timestamps: false },
)
class Grademapping extends Sequelize.Model {}
Grademapping.init(
{
_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
sectionID: {
type: Sequelize.INTEGER,
references: {
model: 'section',
key: '_id',
},
},
studentID: {
type: Sequelize.INTEGER,
references: {
model: 'student',
key: '_id',
},
}
},
{ sequelize, tableName: 'grademapping', timestamps: false },
)
student.belongsToMany(section,{through: grademapping})
section.belongsToMany(student,{through: grademapping})

Sqlite Foreign key mismatch sequelize migration

My request SQL fail when I try to insert data in my table PostVotes
I use sequelize migration to migrate my database and I have the same probleme when I make my sql request in my console.
sequelize db:migrate
When I use sequelize.sync() i don't have this problem
My table:
/* TABLE Users */
queryInterface.createTable('Users', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
},
password: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
}),
queryInterface.createTable('Posts', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
},
title: {
type: Sequelize.STRING,
allowNull: false,
},
userId: {
type: Sequelize.UUID,
primaryKey: true,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'id',
},
},
}),
/* Table posts votes*/
queryInterface.createTable('PostVotes', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
},
vote: {
// eslint-disable-next-line new-cap
type: Sequelize.ENUM('up', 'down'),
validate: {
isIn: [['up', 'down']],
},
allowNull: false,
},
userId: {
type: Sequelize.UUID,
primaryKey: true,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'id',
},
},
postId: {
type: Sequelize.UUID,
primaryKey: true,
onDelete: 'CASCADE',
references: {
model: 'Posts',
key: 'id',
},
},
}),
[Error: SQLITE_ERROR: foreign key mismatch - "PostVotes" referencing "Posts"]
I already find answer but nothing is working. I think my mistake is in the table PostVotes but I don't understand what.
Thanks !
FIX
queryInterface.createTable('Posts', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
},
title: {
type: Sequelize.STRING,
allowNull: false,
},
userId: {
type: Sequelize.UUID,
primaryKey: true, # DELETE THIS ONE
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'id',
},
},
}),
I delete primaryKey in table Post column userId

Inserting data in multiple tables using Sequelize

It's my first time using Sequelize with MySQL and would like to understand how to insert data into two tables with a foreign key dependency.
Let's say, I have two tables - bookingDescription and bookingSummary. The entities for the same are as follows
//bookingSummary
module.exports = (sequelize, DataTypes) => {
return sequelize.define('bookingSummary', {
headerId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,},
titleId: DataTypes.STRING,
abNumber: DataTypes.INTEGER,
userProfileId: DataTypes.INTEGER,
theatreId: DataTypes.STRING,
mFId: DataTypes.STRING,
createdBy: { type: DataTypes.TEXT, allowNull: false },
modifiedBy: { type: DataTypes.TEXT, allowNull: false },
status: DataTypes.STRING
}, {
tableName: 'booking_summary',
underscored: true
})
}
//bookingDescription
module.exports = (sequelize, DataTypes) => {
return sequelize.define('bookingWeek', {
lineId: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true,},
headerId: DataTypes.STRING,
titleId: DataTypes.STRING,
abNumber: DataTypes.INTEGER,
theatreId: DataTypes.STRING,
mFId: DataTypes.STRING,
theatreName: DataTypes.STRING,
city: DataTypes.STRING,
state: DataTypes.STRING,
playStartDate: DataTypes.DATE,
playEndDate: DataTypes.DATE,
preferredFormat: DataTypes.INTEGER,
screensInDay: DataTypes.INTEGER,
featureTypeFlag: DataTypes.TEXT,
cofeatureName: DataTypes.STRING,
exhbtrReqComment: DataTypes.STRING,
createdBy: { type: DataTypes.TEXT, allowNull: false },
modifiedBy: { type: DataTypes.TEXT, allowNull: false },
status: DataTypes.STRING
}, {
tableName: 'booking_description',
underscored: true
})
}
Foreign key references in bookingSummary are as follows
FOREIGN KEY (headerId) REFERENCES bookingSummary(headerId)
FOREIGN KEY (titleId, abNumber, mFId)
REFERENCES bookingSummary(abNumber)
I have an object of data which needs to be inserted into the tables at an instant.
Any idea on how to approach this ?
So, i would recommend you first learning about SQL relations, regardless of Sequelize, and your current project structure, because it seems to me that you still lack the basic understanding of the logic behind these associations, where they should be used and how.
Both your tables have duplicate fields, which makes no sense. Take a look here, for example: https://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561
As for your current code, i played with it a bit, and this is what i did(will work only if you're using model.sync(), because a column needs to be created automatically. Also use force:true if you already have the tables):
module.exports = (sequelize, DataTypes) => {
const bookingHeader = sequelize.define('bookingHeader', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
abNumber: DataTypes.INTEGER,
userProfileId: DataTypes.INTEGER,
theatreId: DataTypes.STRING,
mFId: DataTypes.STRING,
createdBy: { type: DataTypes.TEXT, allowNull: true },
modifiedBy: { type: DataTypes.TEXT, allowNull: true },
status: DataTypes.STRING
}, {
tableName: 'booking_header',
// underscored: true
})
bookingHeader.associate = function (models) {
bookingHeader.hasOne(models.bookingDescription);
};
return bookingHeader;
}
Booking description:
module.exports = (sequelize, DataTypes) => {
const bookingDescription = sequelize.define('bookingDescription', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, },
abNumber: DataTypes.INTEGER,
theatreId: DataTypes.STRING,
mFId: DataTypes.STRING,
theatreName: DataTypes.STRING,
city: DataTypes.STRING,
state: DataTypes.STRING,
playStartDate: DataTypes.DATE,
playEndDate: DataTypes.DATE,
preferredFormat: DataTypes.INTEGER,
screensInDay: DataTypes.INTEGER,
featureTypeFlag: DataTypes.TEXT,
cofeatureName: DataTypes.STRING,
exhbtrReqComment: DataTypes.STRING,
createdBy: { type: DataTypes.TEXT, allowNull: false },
modifiedBy: { type: DataTypes.TEXT, allowNull: false },
status: DataTypes.STRING
}, {
tableName: 'booking_description',
// underscored: true
})
bookingDescription.associate = function (models) {
bookingDescription.belongsTo(models.bookingHeader);
};
return bookingDescription;
}
In your route, you can do something like this:
const {bookingHeader,bookingDescription} = models;
app.post("/booking", async (req, res, next) => {
try {
const header = await bookingHeader.create(req.body)
const headerId = header.id
await bookingDescription.create({state:'active',createdBy:'somebody',modifiedBy:'somebody',bookingHeaderId:headerId})
res.json(header);
} catch (error) {
console.log(error)
res.status(500)
}
});
Notice that i hardcoded some of the fields for the description, just for example purposes. Also, it's possible that there is a "better" way to do this with Sequelize, but the docs are really poor, so this gets the job done.

Sequelize.js - "is not associated to"

I have some issue with getting full data from db.
That are my models:
User
module.exports = function(sequelize, DataTypes) {
return sequelize.define('user', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'ID'
},
password: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'password'
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'email'
},
roleId: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'role',
key: 'ID'
},
field: 'role_id'
}
}, {
timestamps: false,
tableName: 'user'
});
};
Role
module.exports = function(sequelize, DataTypes) {
return sequelize.define('role', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'ID'
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'name'
},
description: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'description'
},
permission: {
type: DataTypes.INTEGER(11),
allowNull: false,
field: 'permission'
}
}, {
timestamps: false,
tableName: 'role',
});};
I want to get object of one specific user including all role content.
Somethink like
{
id: 4,
password: 'xxx',
email: 'adsads#saas.com',
role: {
id: 2,
name: 'admin'
description: 'ipsum ssaffa',
permission: 30
}
}
So I'm using:
User.findOne( { where: { id: req.userId }, include: [ Role ] } ).then( user =>{...});
but I get in the result err.message: "role is not associated to user"
And the simple question - what's wrong ? :)
*to handle models I'm using sequelize-cli
You get this error because you didn't add associate between the models
base on your json I see that each user only has one role, so you can either use belongsTo in role model or hasOne in user model
Should be something like this:
User.js
module.exports = function(sequelize, DataTypes) {
var user = sequelize.define('user', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'ID'
},
password: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'password'
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'email'
},
roleId: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'role',
key: 'ID'
},
field: 'role_id'
}
}, {
timestamps: false,
tableName: 'user'
});
user.associate = function(models) {
user.hasOne(models.role, {foreignKey: 'id',sourceKey: 'roleId'});
}
return user;
};
Role.js
module.exports = function(sequelize, DataTypes) {
var role = sequelize.define('role', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
field: 'ID'
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
field: 'name'
},
description: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'description'
},
permission: {
type: DataTypes.INTEGER(11),
allowNull: false,
field: 'permission'
}
}, {
timestamps: false,
tableName: 'role',
});
role.associate = function(models) {
user.belongsTo(models.role, {foreignKey: 'id'});
}
return role;
};
You have to declare associations between your Models. If using Sequelize CLI make sure the static method associate is being called. Example:
/models.index.js
const Category = require('./Category');
const Product = require('./Product');
const ProductTag = require('./ProductTag');
const Tag = require('./Tag');
Category.associate({Product});
Product.associate({Category,Tag});
Tag.associate({Product});
module.exports={Category,Product,ProductTag,Tag};
and then the association in Category.js
'use strict';
const {Model,DataTypes} = require('sequelize');
const sequelize = require('../config/connection.js');
class Category extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method.
*/
static associate({Product}) {
// define association here
console.log('Category associated with: Product');
this.hasMany(Product, {
foreignKey: 'category_id',
onDelete: 'CASCADE'
});
}
}
Category.init({
category_id: {type: DataTypes.INTEGER, autoIncrement: true, allowNull: false, primaryKey: true},
category_name: {type: DataTypes.STRING, allowNull: false}
}, {
sequelize,
timestamps: false,
freezeTableName: true,
underscored: true,
modelName: "Category",
});
module.exports = Category;

Categories