Sequilize Mysql Foreign Key is null - javascript

These are my models
Files
exports.models = File = sequelize.define("File", {
originalname: {
type: DataTypes.STRING,
allowNull: false,
},
destination: {
type: DataTypes.STRING,
allowNull: false,
},
filename: {
type: DataTypes.STRING,
allowNull: false,
},
path: {
type: DataTypes.STRING,
allowNull: false,
},
});
Sales
exports.models = Sales = sequelize.define("sales", {
OrderDate: {
type: DataTypes.STRING,
allowNull: false,
},
Region: {
type: DataTypes.STRING,
allowNull: false,
},
City: {
type: DataTypes.STRING,
allowNull: false,
},
Category: {
type: DataTypes.STRING,
allowNull: false,
},
Product: {
type: DataTypes.STRING,
allowNull: false,
},
Quantity: {
type: DataTypes.STRING,
allowNull: false,
},
UnitPrice: {
type: DataTypes.STRING,
allowNull: false,
},
TotalPrice: {
type: DataTypes.STRING,
allowNull: false,
},
});
and now I add the relation
await File.hasMany(Sales);
await Sales.belongsTo(File);
await sequelize
.sync({ force: true })
.then(async () => {
console.log("Database & tables created!");
})
.catch((err) => {
console.log("Error: " + err);
});
});
now with the sync method
the ORM Creates my Tables with all the columns that I have defined and additionally, it will create an id column in both the Sales and Files Tables automatically along with a FileID column in the Sales table as a foreign key
And Now
try {
await File.create(req.file);
} catch (err) {
console.log(err);
res
.status(500)
.json({ message: "Server Error File NOt Uploaded To Database" });
return;
}
try {
await Sales.bulkCreate(data);
} catch (error) {
console.log(error);
res
.status(500)
.json({ message: "Internal Server Error Data canot be uploaded" });
return;
}
when I try to insert data into my Database all the data is inserted correctly except for the foreign key which is null
I tried putting the NOT Null Constrain in there but after I do that the database returns an error which basically says that this table can not have this constrain
to my knowledge I have tried everything under sun and I really need help
Thank you in advance

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.

Sequelize "include" not working white many-to-many relations

I'm new to Node and Sequelize, and i'm building a basic eCommerce.
These are my models:
const Product = sequelize.define('product', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
});
const Sale = sequelize.define('sale', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
isDelivered: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
});
And these the relations:
Sale.belongsToMany(Product, { through: SaleItem });
Product.belongsToMany(Sale, { through: SaleItem });
The problem starts when I try to get the "SaleItems"
SaleItem.findAll({
include: [Product],
})
.then(response => {
console.log(response);
})
I get the response:
SequelizeEagerLoadingError: product is not associated to saleItem!
It's strange, couse I'm doing the same on a one-to-many relation, and works perfectly.
Thanks for your time :)
You have associations between Product and Sale but not between them and SaleItem.
Your existing associations let you execute only queries like this:
Sale.findAll({
include: [Product],
})
.then(response => {
console.log(response);
})
Product.findAll({
include: [Sale],
})
.then(response => {
console.log(response);
})
You need to add associations for SaleItem like this:
SaleItem.belongsTo(Product);
SaleItem.belongsTo(Sale);
in order to get SaleItem records along with associated model instances.

getting a json object with array images return unexpected end of json

I am sure it has been handled before, but I have not been able to find another answer to the situation from google. When I use postman to get a route, it returns the following errors:
[0] SyntaxError: Unexpected end of JSON inpu
[0]at JSON.parse ()
[0]at model.get (C:\Users\EA_Ma\Desktop\App-projects\majeksCorp\models\Services.js:55:23)
[0] at model.get (C:\Users\EA_Ma\Desktop\App-projects\majeksCorp\node_modules\sequelize\lib\model.js:3465:41)
[0] at model.get (C:\Users\EA_Ma\Desktop\App-projects\majeksCorp\node_modules\sequelize\lib\model.js:3499:33)
[0] at model.toJSON (C:\Users\EA_Ma\Desktop\App-projects\majeksCorp\node_modules\sequelize\lib\model.js:4368:12)
[0] at JSON.stringify ()
[0] at stringify (C:\Users\EA_Ma\Desktop\App-projects\majeksCorp\node_modules\express\lib\response.js:1123:12)
[0] at ServerResponse.json (C:\Users\EA_Ma\Desktop\App-projects\majeksCorp\node_modules\express\lib\response.js:260:14)
[0] at C:\Users\EA_Ma\Desktop\App-projects\majeksCorp\routes\api\services.js:179:30
[0] at processTicksAndRejections (internal/process/task_queues.js:97:5)
This is the affected schema:
"use script";
module.exports = (sequelize, Datatypes) => {return sequelize.define("service",{
id: {
type: Datatypes.UUID,
primaryKey: true,
defaultValue: Datatypes.UUIDV4,
title: {
type: Datatypes.STRING,
required: true,
allowNull: true,
},
category: {
type: Datatypes.STRING,
required: true,
allowNull: true,
},
description: {
type: Datatypes.STRING,
required: true,
allowNull: true,
},
picture: {
type: Datatypes.STRING,
},
service_gallery: {
type: Datatypes.STRING,
defaultValue: null,
get: function () {
return JSON.parse(this.getDataValue("service_gallery"));
},
set: function (val) {
return this.setDataValue("service_gallery", JSON.stringify(val));
},
allowNull: true,
},
date: {
//Exakt den datum som personen registrera sig
type: Datatypes.DATE,
defaultValue: Datatypes.NOW,
},
//This is the columns or database
updated_at: { type: Datatypes.DATE },
deleted_at: { type: Datatypes.DATE },
},
{
underscored: true, //This is created for it
paranoid: true, //Database won't really delete information from database.
}
);
};
This was the method I called.
router.get("/:category/:title", async(req, res) => {
const errors = {};
await db.service.findOne({
where: {[Op.and]: [{category: req.params.category}, {title: req.params.title}]}
})
.then((service) => {
if (!service) {
errors.noservice = "Nothing was found";
res.status(404).json(errors);
return;
}
if(service) return res.json(service);
})
.catch((err) => console.log(err));
});
I think the error is originating from this line in the Schema:
return JSON.parse(this.getDataValue("service_gallery"));

Store request/reponse into a database table in NodeJS Express

I’m trying
to create a mini Wireshark/debuging playground
I want to store all the requests & responses that pass through my API Back End so I can leverage them to debug what was going on.
The main goal is to generate the logs table on a web page with the ability to export as JSON format.
I have
an API written in Node JS using Express connecting to Postgres Database via Sequelize
I have a lot a requests come through my API.
Here are an example my requests
POST /api/login
POST /api/getSessionTimeOut
POST /api/checkIfGroupExist/25050-telenet
POST /api/listUsersInGroup/25050-telenet
POST /api/primary/createVxLan/ingress/103
POST /api/primary/createVxLan/egress/103
POST /api/primary/createSwitch/103
POST /api/primary/createVxLan/ingress/104
POST /api/primary/createVxLan/egress/104
POST /api/primary/createSwitch/104
POST /api/backup/createVxLan/ingress/103
POST /api/backup/createVxLan/egress/103
POST /api/backup/createSwitch/103
POST /api/backup/createVxLan/ingress/104
POST /api/backup/createVxLan/egress/104
POST /api/backup/createSwitch/104
POST /api/primary/installDevice
POST /api/monitor/2724
...
POST /api/monitor/2724
POST /api/backup/installDevice
POST /api/monitor/2725
...
POST /api/monitor/2725
POST /api/createDynamicInterface/ingress/103
POST /api/createDynamicInterface/egress/103
POST /api/createDynamicInterface/ingress/104
POST /api/createDynamicInterface/egress/104
POST /api/createPolicyFirewall/v4/103/vpn
POST /api/createPolicyFirewall/v4/104/inline
POST /api/createPolicyFirewall/v4/103/inline
POST /api/createPolicyFirewall/v4/103/inline
POST /api/createPolicyFirewall/v6/103/vpn
POST /api/createPolicyFirewall/v6/103/inline
POST /api/createPolicyFirewall/v6/104/inline
POST /api/createPolicyFirewall/v6/103/inline
POST /api/installPackage/inline
POST /api/monitor/2726
...
POST /api/monitor/2726
POST /api/installPackage/vpn
POST /api/monitor/2727
...
POST /api/monitor/2727
I would like to store each request into a logs table in my database.
I’ve tried
Migration
module.exports = {
up: (queryInterface, Sequelize) =>
queryInterface.sequelize.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
.then(() => {
queryInterface.createTable('Logs', {
id: {
allowNull: false,
primaryKey: true,
type: Sequelize.Sequelize.UUID,
defaultValue: Sequelize.literal('uuid_generate_v4()')
},
user: {
type: Sequelize.STRING,
allowNull: true
},
accountId: {
type: Sequelize.STRING,
allowNull: true
},
cpeMac: {
type: Sequelize.STRING,
allowNull: false
},
pHnsId: {
type: Sequelize.STRING,
allowNull: true
},
gHnsId: {
type: Sequelize.STRING,
allowNull: true
},
serviceType: {
type: Sequelize.STRING,
allowNull: true
},
securityCluster: {
type: Sequelize.STRING,
allowNull: true
},
method: {
type: Sequelize.STRING,
allowNull: true
},
portalUrl: {
type: Sequelize.STRING,
allowNull: true
},
apiUrl: {
type: Sequelize.STRING,
allowNull: true
},
data: {
type: Sequelize.STRING,
allowNull: true
},
response: {
type: Sequelize.STRING,
allowNull: true
},
createdAt: {
type: Sequelize.DATE,
allowNull: false
},
updatedAt: {
type: Sequelize.DATE,
allowNull: false
},
deletedAt: {
type: Sequelize.DATE,
allowNull: true
}
})
}),
down: (queryInterface) => queryInterface.dropTable('Logs')
};
Model
module.exports = (sequelize, DataTypes) => {
const Log = sequelize.define('Log', {
user: {
type: DataTypes.STRING,
allowNull: true
},
accountId: {
type: DataTypes.STRING,
allowNull: true
},
cpeMac: {
type: DataTypes.STRING,
allowNull: false
},
pHnsId: {
type: DataTypes.STRING,
allowNull: true
},
gHnsId: {
type: DataTypes.STRING,
allowNull: true
},
serviceType: {
type: DataTypes.STRING,
allowNull: true
},
securityCluster: {
type: DataTypes.STRING,
allowNull: true
},
method: {
type: DataTypes.STRING,
allowNull: true
},
portalUrl: {
type: DataTypes.STRING,
allowNull: true
},
apiUrl: {
type: DataTypes.STRING,
allowNull: true
},
data: {
type: DataTypes.STRING,
allowNull: true
},
response: {
type: DataTypes.STRING,
allowNull: true
}
});
const schema = {
user: "user",
accountId: "accountId",
cpeMac: "cpeMac",
pHnsId: "pHnsId",
gHnsId: "gHnsId",
serviceType: "serviceType",
securityCluster: "securityCluster",
method: "method",
portalUrl: "portalUrl",
apiUrl: "apiUrl",
data: "data",
response: "response"
};
Log.list = (models) => new Transformer.List(models, schema).parse();
Log.single = (model) => new Transformer.Single(model, schema).parse();
return Log;
};
Controller
const Log = require('../models').Log;
module.exports = (config, jwtDecode, Op) => {
let logs = {};
/**
* Create a Log
*
* #return {object} log
*/
logs.create = async(req, res, next) => {
try {
let $body = {
name: log.name,
accountId: log.accountId,
cpeMac: log.cpeMac,
pHnsId: log.pHnsId,
gHnsId: log.gHnsId,
serviceType: log.serviceType,
securityCluster: log.securityCluster,
method: log.method,
portalUrl: log.portalUrl,
apiUrl: log.apiUrl,
data: log.data,
response: log.response
};
let response = await Log.create($body);
res.status(200).send(JSON.parse(response));
} catch (error) {
next(error);
}
};
return logs;
};
Service
module.exports = (config, request) => {
let log = {};
/*==============================
= create =
==============================*/
log.create = ($body) => {
let $options = {
method: "POST",
uri: `/api/logs/create`,
body: $body
};
return new Promise((resolve, reject) => {
request($options)
.then(data => resolve(JSON.stringify(data)))
.catch(error => reject(error));
});
};
return log;
};
route
app.post('/api/logs/create', controllers.logs.create);
Result
Now, that I have all of the pieces ready to go, but I am not sure how to connect all of these to be able to store all the requests/responses in the database?
As a basic outline for creating this as middleware, you would do something like this:
App.js
/* You're imports and setup */
/*
any time a call is made, it will hit this function
app.use accepts a function, which will give the parameters
req, res, next.
i.e. app.use((req, res, next) => { ... })
so we'll pass in you're logs.create function
and the request will have all the information on what
endpoint is being given.
*/
app.use(controllers.logs.create)
/* the rest of your routes */
If you provide your app.js file, I can give you a better version of what is above
Let me know if there is anything else I can do.

Error in sequelize column is not found

I have created the following model in sequelize:
export function initialize(sequelize: Sequelize.Sequelize, dataTypes: Sequelize.DataTypes): SalesPerson.Model {
var salesPersonModel = sequelize.define<SalesPerson, SalesPerson.Pojo>('salesPerson', {
ownerId: { type: dataTypes.STRING, allowNull: false, field: 'owner_id' },
firstName: { type: dataTypes.STRING, allowNull: false, field: 'first_name' },
lastName: { type: dataTypes.STRING, allowNull: false, field: 'last_name' },
email: { type: dataTypes.STRING, allowNull: false }
}, {
underscored: true,
tableName: 'sales_persons'
});
salesPersonModel.removeAttribute('id');
return salesPersonModel;
}
after starting sequelize.sync() the table is correctly created. the problem is that when I make a query like this:
db.SalesPerson.find({ limit: 1, order: [['updated_at DESC']] })...
I got the following error:
Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'salesPerson.updated_at DESC' in 'order clause'
and this has not sense because I see in the database the column so should be something related with sequelize
That's not how the syntax works. You need to separate the column name from the direction:
db.SalesPerson.find({ limit: 1, order: [['updated_at', 'DESC']] })...

Categories