I have 2 table schemas Customer and Cart
Customer.js
module.exports = (sequelize, DataTypes) => {
const Customer = sequelize.define("custom", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
title: {
type: DataTypes.STRING,
allowNull: false
},
username: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
address: {
type: DataTypes.STRING,
allowNull: true
},
date: {
type: DataTypes.STRING,
allowNull: false,
}
}, {
timestamps: false
});
Customer.associate = (models) => {
Customer.hasOne(models.cart, { foreignKey: 'customerId' });
};
return Customer;
};
Cart.js
module.exports = (sequelize, DataTypes) => {
const Cart = sequelize.define("cart", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
customerId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'custom',
key: 'id'
}
}
}, {
timestamps: false
});
Cart.associate = (models) => {
// Define associations here
Cart.belongsTo(models.customer, { foreignKey: 'customerId' });
};
return Cart;
};
I have index.js file for each models
customer/index.js
const dbConfig = require("../../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.customer = require("./customer.js")(sequelize, Sequelize);
db.cart = require("../cart/cart.js")(sequelize, Sequelize);
db.customer.associate(db);
module.exports = db;
cart/index.js
const dbConfig = require("../../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.cart = require('./cart.js')(sequelize, Sequelize);
db.customer = require('../customer/customer.js')(sequelize, Sequelize);
db.customer.associate(db);
module.exports = db;
and my server.js or the main file I am running
const express = require('express');
const cors = require("cors");
const session = require('express-session');
const crypto = require('crypto');
const app = express();
var corsOptions = {
origin: "http://localhost:3000"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Generate a random secret key
const secretKey = crypto.randomBytes(32).toString('hex');
app.use(session({
secret: secretKey,
resave: false,
saveUninitialized: false
}));
const db_customer = require("./app/database/models/customer/index.js");
// const db_product = require("./app/database/models/product/index.js");
// db.sequelize.sync();
db_customer.sync();
const PORT = 4000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
after running node server.js
i am getting this error
at Socket.emit (node:events:518:28)
at addChunk (node:internal/streams/readable:559:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
at Readable.push (node:internal/streams/readable:390:5) {
code: ‘ER_CANT_CREATE_TABLE’,
errno: 1005,
sqlState: ‘HY000’,
sqlMessage: ‘Can’t create table s3941488_fsd_a2
.carts
(errno: 150 “Foreign key constraint is incorrectly formed”)’,
sql: ‘CREATE TABLE IF NOT EXISTS carts
(id
INTEGER auto_increment , customerId
INTEGER NOT NULL, PRIMARY KEY (id
), FOREIGN KEY (customerId
) REFERENCES custom
(id
) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;’,
parameters: undefined
},
sql: ‘CREATE TABLE IF NOT EXISTS carts
(id
INTEGER auto_increment , customerId
INTEGER NOT NULL, PRIMARY KEY (id
), FOREIGN KEY (customerId
) REFERENCES custom
(id
) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;’,
parameters: {}
}
It fixed the issue when I removed the references attribute from customerId attribute in the cart model schema, but I require for data integrity. I am not sure what causes the problem