how can I connect many-to-many tables in sequelize? - javascript

`I have a data base in my localhost and I want to show the "tickets" of an "passenger". I'm working with nodejs, mysql2 and sequelize. The structure of the sql is:
CREATE TABLE pasajero (
pasaporte integer PRIMARY KEY,
nombre character varying(20),
pais character varying(20)
);
CREATE TABLE viaje (
codigo integer PRIMARY KEY,
codvuelo character varying(20) REFERENCES vuelo(codigo),
costo integer,
fecha date,
piloto1 integer REFERENCES piloto(id),
piloto2 integer REFERENCES piloto(id)
);
CREATE TABLE ticket (
idpasajero integer REFERENCES pasajero(pasaporte),
codviaje integer REFERENCES viaje(codigo),
PRIMARY KEY (idpasajero, codviaje)
);
For the "ticket" table, "idpasajero" and "codviaje" remained as primary keys, following this model they were defined as follows:
const PasajeroModel = db.define(
"pasajeros",
{
pasaporte: { type: DataTypes.INTEGER, primaryKey: true },
nombre: { type: DataTypes.STRING },
pais: { type: DataTypes.STRING },
},
{
timestamps: false,
}
);
const ViajeModel = db.define(
"viajes",
{
codigo: { type: DataTypes.INTEGER, primaryKey: true },
codvuelo: { type: DataTypes.STRING },
costo: { type: DataTypes.INTEGER },
fecha: { type: DataTypes.DATE },
piloto1: { type: DataTypes.INTEGER },
piloto2: { type: DataTypes.INTEGER },
},
{
timestamps: false,
}
);
const TicketModel = db.define(
"tickets",
{
idpasajero: {
type: DataTypes.INTEGER,
primaryKey: true
},
codviaje: {
type: DataTypes.INTEGER,
primaryKey: true
},
},
{
timestamps: false,
}
);
PasajeroModel.belongsToMany(ViajeModel, { through: TicketModel ,foreignKey:"pasaporte"});
ViajeModel.belongsToMany(PasajeroModel, { through: TicketModel ,foreignKey:"codigo"});
Mi actual controlador es este:
export const misTickets = async (req,res) => {
try{
const tickets = await PasajeroModel.findAll({
where:{
pasaporte: req.params.pasaporte
},
include:[{
model: ViajeModel
}]
})
res.json(tickets)
}
catch(err){
res.json({message: err.message})
}
}
I tried to test the code in Thunder CLient and it gave me this message:
{
"message": "Unknown column 'viajes->tickets.pasajeroPasaporte' in 'field list'"
}`

In foreignKey options of belongsToMany associations you should indicate a field from a junction table (Ticket in your case):
PasajeroModel.belongsToMany(ViajeModel, { through: TicketModel ,foreignKey:"idpasajero"});
ViajeModel.belongsToMany(PasajeroModel, { through: TicketModel ,foreignKey:"codviaje"});
And Ticket model should have its own primary key.

Related

Generated table using belongstomany is not associated with any table

I have three tables companies, subscriptions and companySubscription. As name defined company can canbuy/have plan or one subscription belongs to many companies.
So in model/schema I have defined as follows:
companies.js
const sequelize = require("../utils/database");
const bcrypt = require("bcrypt");
const { DataTypes, Model } = require("sequelize");
const subscription = require("./subscriptions");
const CompanySubscription = require("./companySubscription");
class companies extends Model {}
companies.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
contactNo: {
type: DataTypes.STRING,
allowNull: true,
},
companySize: {
type: DataTypes.INTEGER,
allowNull: true,
},
},
{ sequelize, modelName: "companies" }
);
subscription.belongsToMany(companies, { through: CompanySubscription });
module.exports = companies;
subscription.js
const sequelize = require("../utils/database");
const { DataTypes, Model } = require("sequelize");
class subscription extends Model {}
subscription.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
subscriptionPlanType: {
type: DataTypes.ENUM,
values: ["Yearly", "Monthly"],
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
memberCount: {
type: DataTypes.INTEGER,
allowNull: false,
},
amount: {
type: DataTypes.FLOAT,
allowNull: false,
},
},
{ sequelize, modelName: "subscription" }
);
module.exports = subscription;
companySubscription.js
const sequelize = require("../utils/database");
const companies = require("./companies");
const subscription = require("./subscriptions");
const { DataTypes, Model } = require("sequelize");
class CompanySubscription extends Model {}
CompanySubscription.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
status: {
type: DataTypes.ENUM,
values: ["active", "inactive"],
},
subscriptionType: {
type: DataTypes.ENUM,
values: ["Yearly", "Monthly"],
},
subscriptionPlanStartDate: {
type: DataTypes.DATE,
},
subscriptionPlanEndDate: {
type: DataTypes.DATE,
},
paidStatus: {
type: DataTypes.ENUM,
values: ["paid", "unpaid"],
},
paidDate: {
type: DataTypes.DATE,
},
},
{ sequelize, modelName: "CompanySubscription" }
);
module.exports = CompanySubscription;
In controller file I am able to manage to insert the data. Below is the code:
const addBIlling = async (req, res) => {
const foundSubcscription = await subscription.create({
subscriptionPlanType: "Monthly",
name: "s1",
memberCount: 15,
amount: 50.55,
});
const foundCompany = await companies.create({
name: "company1",
email: "company1#gmail.com",
contactNo: "87964644",
companySize: 20,
});
const insertedData = await foundSubcscription.addCompany(foundCompany, {
through: {
status: "active",
paidStatus: "paid",
subscriptionType: "Monthly",
subscriptionPlanEndDate: moment().add(1, "months"),
paidDate: moment().add(1, "months"),
},
});
console.log("inserted data ", insertedData);
res.json({ data: insertedData });
};
Now I want to fetch the records from db as which company has bought which subscription plan!
i.e. company name, subscription plan and its active and paid status and plan's expiry date.
I tried below code:
const billingList = async (req, res) => {
const billingData = await CompanySubscription.findAll({
include: [{ model: companies }],
});
console.log("billing data ", billingData);
};
Above code is throwing error "companies is not associated to CompanySubscription!".
Where have I made a mistake?
Don't try to import models to each other's modules directly. Define model registration functions in each model module and use them all to register models in one place/module and for associations you can define associate function inside each registration function and call them after ALL your models are already registered. That way you won't have cyclic dependencies and all associations will be correct.
See my answer here to get an idea how to do it.

Column Cannot be NULL even if value is defined

I'm trying to seed data into a database and I'm getting this error:
name: 'SequelizeDatabaseError',
parent: Error: Column 'id' cannot be null
code: 'ER_BAD_NULL_ERROR',
errno: 1048,
sqlState: '23000',
sqlMessage: "Column 'id' cannot be null"
Here is the index to seed the data:
const seedUsers = require('./user-seeds');
const seedPosts = require('./post-seeds');
const seedComments = require('./comment-seeds');
const seedVotes = require('./vote-seeds');
const sequelize = require('../config/connection');
const seedAll = async () => {
await sequelize.sync({ force: true });
console.log('--------------');
await seedUsers();
console.log('--------------');
await seedPosts();
console.log('--------------');
await seedComments();
console.log('--------------');
await seedVotes();
console.log('--------------');
process.exit(0);
};
seedAll().catch(err => console.log('seedAll error: ', err));
the error seems to be thrown when seedPost() is called,
the following is the corresponding model:
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/connection');
// create Post Model
class Post extends Model {
static upvote(body, models) {
return models.Vote.create({
user_id: body.user_id,
post_id: body,post_id
}).then(() => {
return Post.findOne({
where: {
id: body.post_id
},
attributes: [
'id',
'post_url',
'title',
'created_at',
[sequelize.literal('(SELECT COUNT(*) FROM vote WHERE post.id = vote.post_id)'), 'vote_count']
],
include: [
{
model: models.Comment,
attributes: ['id', 'comment_text', 'post_id', 'user_id', 'created_at'],
include: {
model: models.User,
attributes: ['username']
}
}
]
});
});
}
}
// create field/column for Post model
Post.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoincrement: true
},
title: {
type: DataTypes.STRING,
allowNull: false
},
post_url: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isURL: true
}
},
user_id: {
type: DataTypes.INTEGER,
references: {
model: 'user',
key: 'id'
}
}
},
{
sequelize,
freezeTableName: true,
underscored: true,
modelName: 'post'
}
);
module.exports = Post;
this is what my seed file looks like:
const { Post } = require('../models');
const postdata = [
{
title: 'Donec posuere metus vitae ipsum.',
post_url: 'https://buzzfeed.com/in/imperdiet/et/commodo/vulputate.png',
user_id: 10
},
{
// ... more seeds
}
];
const seedPosts = () => Post.bulkCreate(postdata);
module.exports = seedPosts;
I'm not sure what I'm doing wrong, any help is greatly appreciated!
// create field/column for Post model
Post.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoincrement: true
},
In your Post.init, autoincrement must be autoIncrement. Maybe in your case you'll need to recreate the table

why Virtual Populate not working on Node js and mongoose? Scenario : Product and Review by user

I have review and product model.If user give review on specific product(id) then it is stored in review model database but i donot like to store user review in product model database .so, i used virtual populate in product model instead of child referencing.After using virtual properties,if we use product id to see details,we can see review of user in json format but not saved in database.But the problem is my virtual properties (In Product Model) not working as it doesnt show review of user in json format when i send the request in that product id which already have review by user(stored in review model database).what is the problem here?
User Review on Product (id) stored in database
Sending Request of that product id to see review of user in json format using virtual properties(but no review found in json)
In Product Model
const productSchema = new Schema({
name: {
type: String,
required: true,
trim: true,
},
slug: {
type: String,
required: true,
unique: true,
},
price: {
type: String,
required: true,
},
quantity: {
type: Number,
required: true,
},
description: {
type: String,
required: true,
trim: true,
},
offer: {
type: Number,
},
discount: {
type: Number,
},
productPictures: [{
img: {
type: String,
},
}, ],
mainCategory: {
type: mongoose.Schema.Types.ObjectId,
ref: "category",
required: [true, "It is a required field"],
},
sub1Category: {
type: mongoose.Schema.Types.ObjectId,
ref: "category",
required: [true, "It is a required field"],
},
sub2Category: {
type: mongoose.Schema.Types.ObjectId,
ref: "category",
required: [true, "It is a required field"],
},
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "admin",
required: true,
},
vendor: {
type: mongoose.Schema.Types.ObjectId,
ref: "vendor",
},
createdAt: {
type: String,
default: moment().format("DD/MM/YYYY") + ";" + moment().format("hh:mm:ss"),
},
updatedAt: {
type: String,
default: moment().format("DD/MM/YYYY") + ";" + moment().format("hh:mm:ss"),
},
},
{
toJson: { virtuals: true },
toObject: { virtuals: true },
}
);
productSchema.virtual("reviews", {
ref: "review",
foreignField: "product",
localField: "_id",
// justOne: true
});
const Product = mongoose.model("product", productSchema);
module.exports = Product;
In Review Model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const moment = require("moment");
const reviewSchema = new Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
required: [true, "Review must belong to user"],
},
product: {
type: mongoose.Schema.Types.ObjectId,
ref: "product",
required: [true, "Review must belong to the product"],
},
review: {
type: String,
required: [true, "Review cannot be empty"],
},
rating: {
type: Number,
min: 1,
max: 5,
},
createdAt: {
type: String,
default: moment().format("DD/MM/YYYY") + ";" + moment().format("hh:mm:ss"),
},
updateddAt: {
type: String,
default: moment().format("DD/MM/YYYY") + ";" + moment().format("hh:mm:ss"),
},
}, {
toJson: { virtuals: true },
toObject: { virtuals: true },
});
// pre middleware and populating user and product(we can also do populate in getAllReview in controller)
reviewSchema.pre(/^find/, function(next) {
// ^find here is we use regex and can able to find,findOne ...etc
this.populate({
path: "product",
select: " _id name",
}).populate({
path: "user",
select: " _id fullName",
});
next()
});
const Review = mongoose.model("review", reviewSchema);
module.exports = Review;
In Review.js
const Review = require("../../models/Review.Models")
exports.createReview = async(req, res) => {
const review = await Review.create(req.body)
return res.status(201).json({
status: true,
review
})
}
exports.getAllReviews = async(req, res) => {
try {
const reviews = await Review.find()
return res.status(200).json({
status: true,
totalReviews: reviews.length,
reviews
})
} catch (error) {
return res.status(400).json({
status: false,
error
})
}}
In Product.js
const Product = require("../../models/Product.Models");
exports.getProductDetailsById = async(req, res) => {
try {
const { productId } = req.params;
// const { productId } = req.body;
if (productId) {
const products = await Product.findOne({ _id: productId })
.populate('reviews')
return res.status(200).json({
status: true,
products,
});
} else {
console.log("error display");
return res.status(400).json({
status: false,
error: "params required...",
});
}
} catch (error) {
return res.status(400).json({
status: false,
error: error,
});
}
try this in Product.js
try {
if (productId) {
const products = await Product.findOne({ _id: productId }).populate(
"reviews"
);
console.log(products);
if (products) {
return res.status(200).json({
status: true,
message: "Products is listed",
products,
reviw: products.reviews,
});
only need to add on response sending
return res.status(200).json({
status: true,
message: "Products is listed",
products,
reviw: products.reviews,
});

Sequelize association include returns null

I am having an issue when I'm trying to associate a table into my query with sequelize-cli.
My query works but it doesn't populate Adresse table. Only Patient is populated. Adresse array is ignored. (return null)
I made a one-to-one relationship between the tables and am not sure if that's the cause of the error or if it is somewhere else where I am associating the two tables.
here is my models :
server/models/patient.js
module.exports = (sequelize, Sequelize) => {
const Patient = sequelize.define('Patient', {
///
}, {
classMethods: {
associate: (models) => {
Patient.belongsTo(models.Adresse, {
foreignKey: 'adresseId',
});
}
}
});
return Patient;
};
server/models/adresse.js
module.exports = function(sequelize, Sequelize) {
const Adresse = sequelize.define('Adresse', {
adresse: {
type: Sequelize.STRING,
allowNull: false,
},
complementAdr: {
type: Sequelize.STRING
},
codePostal: {
type: Sequelize.INTEGER,
allowNull: false
},
}, {
classMethods: {
associate: (models) => {
Adresse.hasMany(models.Patient, {
foreignKey: 'adresseId',
as: 'Patients',
});
}
}
});
return Adresse;
};
and here is where I specified the association on my migration files :
server/migrations/20170326145609-create-patient.js
adresseId: {
type: Sequelize.INTEGER,
references: {
model: 'Adresses',
key: 'id_adresse',
as: 'adresseId',
},
},
server/migrations/20170326145502-create-adresse.js
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Adresses', {
id_adresse: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
adresse: {
type: Sequelize.STRING,
allowNull: false,
},
complementAdr: {
type: Sequelize.STRING
},
codePostal: {
type: Sequelize.INTEGER,
allowNull: false
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Adresses');
}
};
and finally here is my query on my controller file :
server/controllers/patients.js
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const Patient = require('../models').Patient;
const Adresse = require('../models').Adresse;
module.exports = {
create(req, res) {
return Patient
.create({
///
adressesId: {
adresse: req.body.adresse,
codePostal: req.body.codePostal,
}
}, {
include: [{
model : Adresse
}]
})
.then(patient => res.status(201).send(patient))
.catch(error => res.status(400).send(error));
}
};
Try using Adresse instead adresseId when eager creating the Adresse model instance related to given Patient
return Patient.create({
// patient attributes,
Adresse: {
adresse: req.body.adresse,
codePostal: req.body.codePostal
},
include: [ Adresse ]
}).then(patient => {
// look at the query generated by this function
// it should create both patient and adresse
});

How to query on shared ids tables on sequelize

I have 4 tables/models that shares ids as primary keys, but for the example I will just show 2
User: {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false
}
Person: {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false
},
name: {
type: Sequelize.STRING
}
I am using shared ids, so the person primary key is the primary key of User, it doesn't have autoimcrement. So is there a way to make a join between those 2 tables? I've tried to do something like:
getAll(){
return User.getAll({
include: [{
model:Person,
}]
})
}
But since there is no relation it doesn't work. What should I do?
Thanks
You cannot use include without a relationship. You could use a raw query to retrieve the information like:
var queryString = 'select * from User u join Person p on u.id = p.id where u.id = :sharedId';
models.sequelize
.query(queryString, {
replacements: { shareId: id},
type: models.sequelize.QueryTypes.SELECT
})
.then(function(result) {
res.json(attendance);
});
But then you would have to implement validations to make sure tables are filled up correclty.
However I would encourage you to implement relationships between your tables as It would be more maintainable. Something like this:
var User = sequelize.define("User", {
id: { type: DataTypes.INTEGER, primaryKey: true},
name: { type: DataTypes.STRING, name: 'name' },
...
}, {
classMethods: {
associate: function(models) {
User.hasOne(models.Person);
}
}
});
var Person = sequelize.define("Person", {
id: { type: DataTypes.INTEGER, primaryKey: true},
name: { type: DataTypes.STRING, name: 'name' },
...
}, {
classMethods: {
associate: function(models) {
Person.belogsTo(models.User);
}
}
});

Categories