I'm having trouble with my Sequelize ORM connection to a MySQL database. I'm receiving a "User is not associated to Bill" error on some requests to the backend server. User and Bill are tables in my Sequelize ORM, and they have a one-to-many relationship. Interestingly, the error disappears when I perform some requests to the server, but appears again when the server establishes a connection to the DB after some period of time.
As a result, some mistakes are happening in my database, such as unexpected NULL values in the BillId.ProductId column.
Here is how I've initialized the connection to the DB in my code:
// bill.model.js
const { DataTypes } = require('sequelize');
const db = require('../../config/db');
const Bill = db.define(
'Bill',
{
// ... Columns definitions
},
);
Bill.associations = function associations(models) {
Bill.hasMany(models.BillItem);
Bill.belongsTo(models.User);
};
module.exports = { Bill };
// config/db.js
const db = new Sequelize(DB_URL, {
logging: false,
});
(async () => {
try {
await db.authenticate();
const { BillItem } = require('../modules/bill_item/bill_item.model');
const { Product } = require('../modules/product/product.model');
const { Bill } = require('../modules/bill/bill.model');
const { User } = require('../modules/user/user.model');
await User.associations({ Bill });
await Bill.associations({ User, BillItem });
await BillItem.associations({ Product, Bill });
await Product.associations({ BillItem });
await db.sync();
} catch (error) {
console.error('Failed to connect with the DB: ', error);
}
})();
module.exports = db;
Can anyone help me identify the issue with my Sequelize ORM connection and why I'm receiving unexpected NULL values in my database?