I'm working on a Node.js project using Sequelize, and I'm encountering an error when trying to fetch associated data with eager loading. Here's the error:
Error fetching cart items: EagerLoadingError [SequelizeEagerLoadingError]: Product is not associated to CartItem!
Here’s the relevant part of my setup:
CartItem Model
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const { CART_ITEM_STATUS } = require("../constants");
const CartItem = sequelize.define(
"CartItem",
{
productId: {
type: DataTypes.INTEGER,
references: {
model: "Products",
key: "id",
},
allowNull: false,
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false,
},
purchasePrice: {
type: DataTypes.FLOAT,
defaultValue: 0,
},
status: {
type: DataTypes.ENUM(
CART_ITEM_STATUS.Not_processed,
CART_ITEM_STATUS.Processing,
CART_ITEM_STATUS.Shipped,
CART_ITEM_STATUS.Delivered,
CART_ITEM_STATUS.Cancelled
),
defaultValue: CART_ITEM_STATUS.Not_processed,
},
},
{
tableName: "cart_items",
timestamps: false,
}
);
module.exports = CartItem;
Product Model
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const CartItem = require("./cartitem");
const Product = sequelize.define(
"Product",
{
id: {
type: DataTypes.STRING(64),
primaryKey: true,
defaultValue: () => {
return crypto.createHash("sha256").update(uuidv4()).digest("hex");
},
},
name: {
type: DataTypes.STRING(255),
allowNull: true,
},
},
{
tableName: "products",
timestamps: false,
}
);
Product.hasMany(CartItem, {
foreignKey: "productId",
as: "items",
});
CartItem.belongsTo(Product, {
foreignKey: "productId",
as: "product",
});
module.exports = Product;
Setup DB
CartItem.belongsTo(Product, { foreignKey: "productId", as: "product" });
Product.hasMany(CartItem, { foreignKey: "productId", as: "cartItems" });
await sequelize.sync({ alter: true });
Query
const cartItems = await CartItem.findAll({
include: [{ model: Product, as: "product" }],
});
Despite defining associations properly, the error persists. What might be causing this issue, and how can I fix it?