How to use add Methods with belongsToMany in Sequelize?

Viewed 421

I am attempting to add a product to my cartitems Table using sequilize:
Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
User.hasOne(Cart);
Cart.belongsTo(User);
Cart.belongsToMany(Product, { through: CartItem });
Product.belongsToMany(Cart, { through: CartItem });

Here is my Product Model:


const Product = sequelize.define('product', {
    id: {
        type: Sequelize.STRING,
        allowNull: false,
        primaryKey: true,
    },
    title: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    price: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
    imageURL: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    description: {
        type: Sequelize.STRING,
        allowNull: false,
    },
});
module.exports = Product;

Here is my Cart Model:

const Cart = sequelize.define('cart', {
    id: {
        type: Sequelize.STRING,
        allowNull: false,
        primaryKey: true,
    },
});
module.exports = Cart;

Here is my User Model:

const User = sequelize.define('user', {
    id: {
        type: Sequelize.STRING,
        allowNull: false,
        primaryKey: true,
    },
    fullName: {
        type: Sequelize.STRING,
        allowNull: false,
    },
    email: {
        type: Sequelize.STRING,
        allowNull: false,
    },
});
module.exports = User;

Here is my Cart-Item Model:

const CarteItem = sequelize.define('carteItem', {
    id: {
        type: Sequelize.STRING,
        allowNull: false,
        primaryKey: true,
    },
    quantity: {
        type: Sequelize.INTEGER,
        allowNull: false,
    },
});
module.exports = CarteItem;

the problem occurs when I attend to Post a product to a cart using

exports.postCart = (req, res, next) => {
    const prodId = req.body.productId;
    let fetchedCart;
    let newQuantity = 1;
    req.user
        .getCart()
        .then((cart) => {
            fetchedCart = cart;
            return cart.getProducts({ where: { id: prodId } });
        })
        .then((products) => {
            let product;
            if (products > 0) product = products[0];
            return Product.findByPk(prodId);
        })
        .then((product) => {
            console.log(product);
            return fetchedCart.addProduct(product, {
                through: { quantity: newQuantity },
            });
        })
        .then(() => {
            res.redirect('/');
        })
        .catch((err) => console.log(err));
};

and I get this error

Executing (default): SELECT `id`, `quantity`, `createdAt`, `updatedAt`, `cartId`, `productId` FROM `carteItems` AS `carteItem` WHERE `carteItem`.`cartId` = '1' AND `carteItem`.`productId` IN ('7c64a81f-59d3-427d-af2a-f9c9ee6e4fde');
AggregateError
    at recursiveBulkCreate (/home/horus/Documents/WorkStation/learningPath/learningPathNode/node-complete-course/node_modules/sequelize/lib/model.js:2600:17)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Function.bulkCreate (/home/horus/Documents/WorkStation/learningPath/learningPathNode/node-complete-course/node_modules/sequelize/lib/model.js:2837:12)
    at async Promise.all (index 0)
    at async BelongsToMany.add (/home/horus/Documents/WorkStation/learningPath/learningPathNode/node-complete-course/node_modules/sequelize/lib/associations/belongs-to-many.js:740:30) {
  errors: [
    BulkRecordError [SequelizeBulkRecordError]: notNull Violation: carteItem.id cannot be null
        at /home/horus/Documents/WorkStation/learningPath/learningPathNode/node-complete-course/node_modules/sequelize/lib/model.js:2594:25
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at async Promise.all (index 0)
        at async recursiveBulkCreate (/home/horus/Documents/WorkStation/learningPath/learningPathNode/node-complete-course/node_modules/sequelize/lib/model.js:2590:9)
        at async Function.bulkCreate (/home/horus/Documents/WorkStation/learningPath/learningPathNode/node-complete-course/node_modules/sequelize/lib/model.js:2837:12)
        at async Promise.all (index 0)
        at async BelongsToMany.add (/home/horus/Documents/WorkStation/learningPath/learningPathNode/node-complete-course/node_modules/sequelize/lib/associations/belongs-to-many.js:740:30) {
      errors: [ValidationError],
      record: [carteItem]
    }
  ]
}
1 Answers

My problem was using the wrong definition of CartItem Schema, should be autoIncremented

Related