sequelize database error with no error message - node.js

It's my first time using PostgreSQL and I'm creating a REST API that using sequelize for postgresql, expressjs and nodejs.
I created a user and each user has many parcels. I am now creating a parcel which belongs to a user using userId as reference. I keep getting the database sequelize error and it has no message. It's routine says, 'checkInsertTarget'.
Error message
{
"name": "SequelizeDatabaseError",
"parent": {
"name": "error",
"length": 190,
"severity": "ERROR",
"code": "42703",
"position": "48",
"file": "d:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_target.c",
"line": "1033",
"routine": "checkInsertTargets",
"sql": "INSERT INTO \"Parcels\" (\"id\",\"name\",\"delivered\",\"presentLoc\",\"destination\",\"description\",\"createdAt\",\"updatedAt\",\"userId\") VALUES (DEFAULT,'Shoe',false,'Onitsha','ESUT','black shoe, size 34','2018-11-25 15:48:13.100 +00:00','2018-11-25 15:48:13.100 +00:00','3') RETURNING *;"
},
"original": {
"name": "error",
"length": 190,
"severity": "ERROR",
"code": "42703",
"position": "48",
"file": "d:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\parser\\parse_target.c",
"line": "1033",
"routine": "checkInsertTargets",
"sql": "INSERT INTO \"Parcels\" (\"id\",\"name\",\"delivered\",\"presentLoc\",\"destination\",\"description\",\"createdAt\",\"updatedAt\",\"userId\") VALUES (DEFAULT,'Shoe',false,'Onitsha','ESUT','black shoe, size 34','2018-11-25 15:48:13.100 +00:00','2018-11-25 15:48:13.100 +00:00','3') RETURNING *;"
},
"sql": "INSERT INTO \"Parcels\" (\"id\",\"name\",\"delivered\",\"presentLoc\",\"destination\",\"description\",\"createdAt\",\"updatedAt\",\"userId\") VALUES (DEFAULT,'Shoe',false,'Onitsha','ESUT','black shoe, size 34','2018-11-25 15:48:13.100 +00:00','2018-11-25 15:48:13.100 +00:00','3') RETURNING *;"
}
Parcel migration code
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Parcels', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
delivered: {
type: Sequelize.BOOLEAN
},
presentLoc: {
type: Sequelize.STRING
},
destination: {
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
userId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'id',
as: 'userId',
}
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Parcels');
}
};
Parcel model code
'use strict';
module.exports = (sequelize, DataTypes) => {
const Parcel = sequelize.define('Parcel', {
name: {
type: DataTypes.STRING,
allowNull: false
},
delivered: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
presentLoc: {
type: DataTypes.STRING,
allowNull: false
},
destination: {
type: DataTypes.STRING,
allowNull: false
},
description: DataTypes.STRING,
}, {});
Parcel.associate = (models) => {
Parcel.belongsTo(models.User, {
foreignKey: 'userId',
onDelete: 'CASCADE'
})
};
return Parcel;
};
Parcel controller
const Parcel = require('../models').Parcel;
const joiSchema = require('../joischema/parcelSchema');
const validator = require('../joischema/validator');
module.exports = {
create(req, res) {
const data = {
name: req.body.name,
description: req.body.description,
destination: req.body.destination,
presentLoc: req.body.presentLoc,
userId: req.params.userId,
};
const valid = validator.isValid(req, res, joiSchema, data);
if (valid != null){
res.status(500).send(valid);
}else{
return Parcel
.create(data)
.then(parcel => res.status(201).send(parcel))
.catch(error => res.status(400).send(error));
}
}

I checked the database and saw a column that I thought I'd removed. I had to run sequelize db:migrate:undo and then sequelize db:migrate again to incorporate my changes i.e. removing that column.

Related

Sequalize relationship betwen same model

I am creating a chat application and trying to create a relationship between User and User through friendship. So far I can create a relationship, but in the end only one user assigned a friend. I'm using Express, sequalize with postgress deployed to heroku. I don't know how to achieve it, any help is appreciated
migration:
`enter code here`await queryInterface.createTable('users', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, } }, }); await queryInterface.createTable('friendships', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, user: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, friend: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, status: { type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'), allowNull: false, defaultValue: 'PENDING', }, });
friendship model:
Friendship.init(
{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
},
user: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
friend: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'users',
key: 'id',
},
},
status: {
type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'),
allowNull: false,
defaultValue: 'PENDING',
},
},
{
sequelize,
underscored: true,
timestamps: false,
modelName: 'friendship',
}
);
associations:
User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user',
otherKey: 'friend' });
Friendship.belongsTo(User, { as: 'info', foreignKey: 'friend' });
controller:
export const addFriend = async (req: Request, res: Response) => {
try {
const { friendId } = req.body;
const userId = req.decodedToken?.id;
const friend = await User.findByPk(friendId, {
attributes: { exclude: ['passwordHash'] },
include: [{ model: User, as: 'friends' }],
});
if (friend)
await Friendship.create({
user: userId,
friend: friend.id,
status: 'PENDING',
});
return res.status(200).json({ status: 'success' });
} catch (e) {
res.status(500).json({ error: 'The server cannot create the user' });
console.log(e);
}
};
response:
"users": {
"count": 2,
"rows": [
{
"id": "e7c7ce39-953a-45e7-a892-a5f99554382e",
"email": "admin",
"username": "admin",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friends": [
{
"id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"email": "admin2",
"username": "admin",
"passwordHash": "$2b$10$GajlewYeiGvUOOV08YOzLuedV/8.KJNUeHB4WPKlUFxErj91ljfWq",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friendship": {
"id": "a78b9336-f5a6-4153-b3e1-e44dbe1cc7a6",
"user": "e7c7ce39-953a-45e7-a892-a5f99554382e",
"friend": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"status": "PENDING"
}
}
]
},
{
"id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
"email": "admin2",
"username": "admin",
"name": null,
"surname": null,
"age": null,
"public": true,
"image": null,
"friends": []
}
Edit:
I made something like this, it's not perfect, but it's good for me
User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user' });
User.belongsToMany(User, { as: 'friend', through: Friendship, foreignKey: 'friend' });
Please consider a many to many relationship.
An user can be a friend of many users.
Many users can be friends of one user.
You may found the how-to implement in the official doc: here.
Basically, use belongsToMany in both associations:
Implementation
The main way to do this in Sequelize is as follows:
const Movie = sequelize.define('Movie', { name: DataTypes.STRING });
const Actor = sequelize.define('Actor', { name: DataTypes.STRING });
Movie.belongsToMany(Actor, { through: 'ActorMovies' });
Actor.belongsToMany(Movie, { through: 'ActorMovies' });

Sequelize: Create two referenced Rows in same Transaction

I want to create two rows.
First I want to create a tenant and after I want to creae a user who has a reference to the tenant.
I want to do this in one transaction (register).
The tenant would be created, but when sequelize try to create the user I get an error:
Failing row contains
Routine: ExecConstraints
My DB-Mappings:
const TenantMapping = sequelize.define('tenant', {
id: { type: DataTypes.NUMBER, primaryKey: true, autoIncrement: true },
label: { type: DataTypes.STRING, allowNull: false },
name: { type: DataTypes.STRING },
postOfficeBox: { type: DataTypes.STRING },
street: { type: DataTypes.STRING },
houseNo: { type: DataTypes.STRING },
zipCode: { type: DataTypes.STRING, validate: { max: 10 } },
city: { type: DataTypes.STRING },
phone: { type: DataTypes.STRING },
mobilePhone: { type: DataTypes.STRING },
email: { type: DataTypes.STRING, allowNull: false },
website: { type: DataTypes.STRING },
birth: { type: DataTypes.DATE, allowNull: false },
death: { type: DataTypes.DATE }
}, {
...getSequelizeTableSettings({ schema: 'auth' })
});
const UserMapping = sequelize.define('user', {
id: { type: DataTypes.NUMBER, primaryKey: true, autoIncrement: true },
tenantId: { type: DataTypes.NUMBER, allowNull: false },
email: { type: DataTypes.STRING, allowNull: false },
password: { type: DataTypes.STRING, allowNull: false },
role: { type: DataTypes.STRING, allowNull: false },
isActivated: { type: DataTypes.BOOLEAN, allowNull: false },
birth: { type: DataTypes.DATE, allowNull: false },
death: { type: DataTypes.DATE }
}, {
...getSequelizeTableSettings({ schema: 'auth' })
});
My Controller
const response = await sequelize.transaction(async (transaction) => {
try {
const { tenantLabel, email, password } = req.body;
const tenant = await this.tenantRepository.create({
tenantLabel,
email
}, {
transaction
});
const user = await this.userRepository.create({
email,
password,
tenantId: tenant.id,
role: UserRole.ADMIN
}, {
transaction
});
await transaction.commit();
res.status(200).json({
tenant,
user
});
} catch (exception) {
res.status(400).send({
...exception
});
}
});
If I create the tenant and user in two different transactions - it works fine.
What is wrong?
I use PostgreSQL
{
"name": "SequelizeDatabaseError",
"parent": {
"length": 257,
"name": "error",
"severity": "ERROR",
"code": "23502",
"detail": "Failing row contains (22, null, email#mail.com, null, null, f, 2022-01-22 12:07:33.899, null).",
"schema": "auth",
"table": "user",
"column": "tenant_id",
"file": "execMain.c",
"line": "1965",
"routine": "ExecConstraints",
"sql": "INSERT INTO \"auth\".\"user\" (\"id\",\"email\",\"birth\") VALUES (DEFAULT,$1,$2) RETURNING \"id\",\"tenant_id\",\"email\",\"password\",\"role\",\"is_activated\",\"birth\",\"death\";",
"parameters": [
"email#mail.com",
"2022-01-22 12:07:33.899 +00:00"
]
},
"original": {
"length": 257,
"name": "error",
"severity": "ERROR",
"code": "23502",
"detail": "Failing row contains (22, null, email#mail.com, null, null, f, 2022-01-22 12:07:33.899, null).",
"schema": "auth",
"table": "user",
"column": "tenant_id",
"file": "execMain.c",
"line": "1965",
"routine": "ExecConstraints",
"sql": "INSERT INTO \"auth\".\"user\" (\"id\",\"email\",\"birth\") VALUES (DEFAULT,$1,$2) RETURNING \"id\",\"tenant_id\",\"email\",\"password\",\"role\",\"is_activated\",\"birth\",\"death\";",
"parameters": [
"email#mail.com",
"2022-01-22 12:07:33.899 +00:00"
]
},
"sql": "INSERT INTO \"auth\".\"user\" (\"id\",\"email\",\"birth\") VALUES (DEFAULT,$1,$2) RETURNING \"id\",\"tenant_id\",\"email\",\"password\",\"role\",\"is_activated\",\"birth\",\"death\";",
"parameters": [
"email#mail.com",
"2022-01-22 12:07:33.899 +00:00"
]
}
I log my object with I want to create a new row before to try create with sequelize.
console.log('create new something', JSON.stringify(object));
const response = await this.sequelize.create(object, transaction);
In the console I have this:
create new something {"email":"email#mail.com","password":"$2b$04$2vDzrLah9FjhxG.nlIJjluByE28O6bjyIr4s7LXqoFgGwyjHODJMG","role":"ADMIN","tenantId":22,"isActivated":false}
Thats correct. But look in the error message. Sequelize try to create a new user only with email - no password, no role, no tenantId, no isActivated...
TenantRepository:
export class TenantRepository extends Repository<TenantResource> {
constructor() {
super(DB_MAPPINGS.TenantMapping, { identifier: 'id' });
}
public async create(
{ tenantLabel, email }: { tenantLabel: string; email: string; },
{ transaction }: { transaction: Transaction }
): Promise<TenantResource> {
return await this.CREATE({
label: tenantLabel,
email
},
{
transaction
}
);
}
}
UserRepostory:
export class UserRepository extends Repository<UserResource> {
constructor() {
super(DB_MAPPINGS.UserMapping, { identifier: 'id' });
}
public async create(
{ email, password, role, tenantId }: { email: string; password: string; role: UserRole; tenantId: number; },
{ transaction }: { transaction: Transaction }
): Promise<UserResource> {
return await this.CREATE({
email,
password: await this.encryptPassword({ password }),
role,
tenantId,
isActivated: false
},
{
transaction
}
);
}
}
Repository:
export class Repository<T> extends RepositoryHelper<T> {
public async CREATE(
object: Partial<T>,
{ transaction }: { transaction: Transaction }
): Promise<T> {
const response = await this.sequelize.create(object, transaction);
return response.toJSON();
}
}
I found my problem. I have to pass the transaction.
export class Repository<T> extends RepositoryHelper<T> {
public async CREATE(
object: Partial<T>,
{ transaction }: { transaction: Transaction }
): Promise<T> {
const response = await this.sequelize.create(object, { transaction });
return response.toJSON();
}
}

Sequelize PostgresSQL - Column does not exist when it does

I do not understand why my api is calling this column and not courseSection.courseId. from postman
I am building my project using AngularJs, PostgresSQL, NodeJs and Sequelize ORM.
This is my part of my course.contorller.js:
const db = require("../models");
const Course = db.course;
//view course catalogue
exports.retrieveAll = (req, res) => {
Course.findAll({
include: [{
model: db.courseSection,
as: "courseSection"
}, {
model: db.category,
as: "category"
}]
})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message: err.message
});
}); };
This is my course.model.js
module.exports = (sequelize, Sequelize) => {
const Course = sequelize.define(
"course",
{
courseId: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
description: {
type: Sequelize.STRING,
},
creditPrice: {
type: Sequelize.INTEGER,
},
isArchived: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
isDraft: {
type: Sequelize.BOOLEAN,
},
level: {
type: Sequelize.ENUM({
values: [
"PRIMARY 1",
"PRIMARY 2",
"PRIMARY 3",
"PRIMARY 4",
"PRIMARY 5",
"PRIMARY 6",
],
}),
},
createdAt: {
type: Sequelize.DATE,
},
updatedAt: {
type: Sequelize.DATE,
},
},
{
classMethods: {
associate: function (models) {
Course.hasMany(models.CourseSection, {
foreignKey: "courseId",
onDelete: "CASCADE",
});
Course.hasMany(models.Material, {
foreignKey: "courseId",
onDelete: "CASCADE",
});
Course.hasMany(models.Review, {
foreignKey: "courseId",
onDelete: "CASCADE",
});
Course.hasMany(models.Enrolment, {
foreignKey: "courseId",
onDelete: "CASCADE",
});
Course.belongsTo(models.Category, {
foreignKey: "categoryId",
onDelete: "CASCADE",
});
Course.belongsTo(models.User, {
foreignKey: "userId",
onDelete: "CASCADE",
});
},
},
}
);
return Course;
};
My courseSection.js
module.exports = (sequelize, Sequelize) => {
const CourseSection = sequelize.define(
"courseSection",
{
sectionId: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
isArchived: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
createdAt: {
type: Sequelize.DATE,
},
updatedAt: {
type: Sequelize.DATE,
},
},
{
classMethods: {
associate: function (models) {
CourseSection.belongsTo(models.Course, {
foreignKey: "courseId",
onDelete: "CASCADE",
});
},
},
}
);
return CourseSection;
};
My migration for course.js
"use strict";
//npx sequelize migration:generate --name course
module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.createTable("course", {
courseId: {
allowNull: false,
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
},
categoryId: {
type: Sequelize.INTEGER,
onDelete: "CASCADE",
references: {
model: "category",
key: "categoryId",
},
},
userId: {
type: Sequelize.INTEGER,
onDelete: "CASCADE",
references: {
model: "user",
key: "userId",
},
},
name: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
description: {
type: Sequelize.STRING,
},
creditPrice: {
type: Sequelize.INTEGER,
},
isArchived: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
isDraft: {
type: Sequelize.BOOLEAN,
},
level: {
type: Sequelize.ENUM({
values: [
"PRIMARY 1",
"PRIMARY 2",
"PRIMARY 3",
"PRIMARY 4",
"PRIMARY 5",
"PRIMARY 6",
],
}),
},
createdAt: {
type: Sequelize.DATE,
},
updatedAt: {
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
return queryInterface.dropTable("course");
},
};
My migration for courseSection
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.createTable("courseSection", {
sectionId: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
courseId: {
type: Sequelize.INTEGER,
onDelete: "CASCADE",
references: {
model: "course",
key: "courseId",
},
},
isArchived: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
createdAt: {
type: Sequelize.DATE,
},
updatedAt: {
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
return queryInterface.dropTable("courseSection");
},
};
My index.js in /model
my postgres table:
When I do localhost:3000/courses/course, my vscode shows the following error:
Executing (default): SELECT "course"."courseId", "course"."name", "course"."description", "course"."creditPrice", "course"."isArchived", "course"."isDraft", "course"."level", "course"."createdAt", "course"."updatedAt", "course"."categoryCategoryId", "course"."categoryId", "course"."userId", "course"."userUserId", "courseSection"."sectionId" AS "courseSection.sectionId", "courseSection"."name" AS "courseSection.name", "courseSection"."isArchived" AS "courseSection.isArchived", "courseSection"."createdAt" AS "courseSection.createdAt", "courseSection"."updatedAt" AS "courseSection.updatedAt", "courseSection"."courseCourseId" AS "courseSection.courseCourseId", "courseSection"."courseId" AS "courseSection.courseId", "category"."categoryId" AS "category.categoryId", "category"."isArchived" AS "category.isArchived", "category"."name" AS "category.name", "category"."createdAt" AS "category.createdAt", "category"."updatedAt" AS "category.updatedAt" FROM "course" AS "course" LEFT OUTER JOIN "courseSection" AS "courseSection" ON "course"."courseId" = "courseSection"."courseCourseId" LEFT OUTER JOIN "category" AS "category" ON "course"."categoryId" = "category"."categoryId";
I have been on this problem for the past 2 days and I honestly do not know where I went wrong. I hope anyone can help me please.
You defined associations between courseSection and course twice:
in associate methods of a model classes (correct ones)
in index.js without indicating foreignKey option
I suppose you just need to remove associations in index.js and just call associate methods of models in index.js.
Something like
db.category.associate(db.models);
// and so on

Why sequelize returns only one result?

i got some problems while writing code, here is some information:
Models:
'use strict';
module.exports = (sequelize, DataTypes) => {
const news = sequelize.define('news', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
title: DataTypes.STRING,
slug: {
type: DataTypes.STRING(64),
unique: true
},
body: DataTypes.STRING,
postedBy: DataTypes.INTEGER
}, {});
news.associate = function(models) {
models.news.hasMany(models.news_ratings, {
as: 'rate',
foreignKey: models.news_ratings.newsId
})
};
return news;
};
///////////////
'use strict';
module.exports = (sequelize, DataTypes) => {
const news_rating = sequelize.define('news_ratings', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
user: DataTypes.INTEGER,
rating: DataTypes.INTEGER,
newsId: DataTypes.INTEGER
}, {});
news_rating.associate = function(models) {
models.news_ratings.belongsTo(models.news, {
foreignKey: models.news.id
})
};
return news_rating;
};
Controller:
router.get('/news/:from/:count', (req, res, next) => {
if (Number.isInteger(Number(req.params.from)) && Number.isInteger(Number(req.params.count))) {
models.news.findAll({
offset: Number(req.params.from),
limit: Number(req.params.count),
include: [{
as: 'rate',
model: models.news_ratings,
attributes: [
[sequelize.fn('AVG', sequelize.col('rating')), 'rate']
]
}]
})
.then(response => {
console.log(response)
res.json(response)
})
.catch(err => {
console.error(err)
res.status(500).end()
})
} else next()
})
This code returns this result (then fetching /news/0/1):
[{
"id": 1,
"title": "First new",
"slug": "demo:first_new",
"body": "New 1. This is demo ^=^",
"postedBy": 0,
"createdAt": "2020-07-22T13:53:48.000Z",
"updatedAt": "2020-07-22T13:53:48.000Z",
"rate": [
{
"rate": "-0.3333"
}
]
}]
But I have 5 news in my database!
...And then I fetch /news/0/5, i got this:
[
{
"id": 1,
"title": "First new",
"slug": "demo:first_new",
"body": "New 1. This is demo ^=^",
"postedBy": 0,
"createdAt": "2020-07-22T13:53:48.000Z",
"updatedAt": "2020-07-22T13:53:48.000Z",
"rate": [
{
"rate": "0.0000"
}
]
}
]
Look, rate is invalid! It should be -0.3333!
Can someone explain me, why this happen and how to resolve this issue?

nodejs sequelize join 2 table using hasmany

I am new in nodejs. I am creating new app using nodejs. i want to join two table city and state using hasmany relations.
Here is my state model state.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('state', {
name: {
type: DataTypes.STRING(255),
allowNull: true
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
createdAt: {
type: DataTypes.DATE,
allowNull: true
},
updatedAt: {
type: DataTypes.DATE,
allowNull: true
}
}, {
tableName: 'state'
});
};
Here is my city model city.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('city', {
state: {
type: DataTypes.INTEGER(11),
allowNull: true
},
name: {
type: DataTypes.STRING(255),
allowNull: true
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
createdAt: {
type: DataTypes.DATE,
allowNull: true
},
updatedAt: {
type: DataTypes.DATE,
allowNull: true
}
}, {
tableName: 'city'
});
};
This is my citycontroller.js
let City = require('../models').city;
let State = require('../models').state;
let message = require('../../config/message');
let Boom = require('boom');
module.exports = {
listCity: async(request,h) =>{
let stateid = request.query.stateid;
try{
let searchQuery = {};
if(stateid) searchQuery.state = stateid;
let listCity = await City.findAll({ where:searchQuery});
if(listCity.length){
let response = {
"statusCode": 200,
"message":message.DATAFOUND,
"result": listCity
};
return h.response(response).code(200);
}else{
return h.response(response).code(204);
}
}catch(err){
return Boom.badRequest(err.message);
}
},
};
Output:
{
"statusCode": 200,
"message": "Data found",
"result": [
{
"state": 1,
"name": "Los Angeles",
"id": 1,
"createdAt": null,
"updatedAt": null
},
{
"state": 1,
"name": "San Francisco",
"id": 2,
"createdAt": null,
"updatedAt": null
},
{
"state": 5,
"name": "Southhampton",
"id": 3,
"createdAt": null,
"updatedAt": null
}
]
}
Now it listing city details only. but i need to join state details also under each city.
If you want to select the data from the state table than define a relation in the state model.
module.exports = function(sequelize, DataTypes) {
const state = sequelize.define('state', {
name: {
type: DataTypes.STRING(255),
allowNull: true
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
createdAt: {
type: DataTypes.DATE,
allowNull: true
},
updatedAt: {
type: DataTypes.DATE,
allowNull: true
}
}, {
tableName: 'state'
});
state.associate = function(model){
models.state.hasMany(models.city){
foreignKey: 'state'
}
return state;
}
};
Or if you want to select data from the city table than define a similar hasOne relation in city table.

Resources