I am trying to develop a mini shopping site, wherein I am doing this using NodeJs Express and MySQL
my cart could have many products and each product could belong to multiple carts.
Therefore using sequelize,my relations are as follows:
Cart.belongsToMany(Product, { through: CartItem });
Product.belongsToMany(Cart, { through: CartItem });
Now CartItem is another table that maps between cartid and productid.
Each of these table have been designed as follows.
Product
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const Product = sequelize.define('product', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: Sequelize.STRING,
price: {
type: Sequelize.DOUBLE,
allowNull: false
},
imageUrl: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.STRING,
allowNull: false
}
});
module.exports = Product;
Cart
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const Cart = sequelize.define('cart', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
}
});
module.exports = Cart;
CartItem
const Sequelize = require('sequelize');
const sequelize = require('../util/database');
const CartItem = sequelize.define('cartItem', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
quantity: Sequelize.INTEGER
});
module.exports = CartItem;
I am trying to add a product to my cart. The logic is to retrieve the list of all available items in the cart. If the product that I am adding already exists, then I just increase the quantity.Else I add it afresh.
The code to do that is as follows:
module.exports.postCart = (req, res, next) => {
const prodId = req.body.productId;
let fetchedCart;
let qty=1;
req.user.getCart()
.then(cart => {
fetchedCart = cart;
console.log('cart', cart);
return cart.getProducts({where:{id:prodId}});
})
.then(products => {
let productInCart;
if (products.length > 0) {
productInCart = products[0];
}
if (productInCart) {
const oldQuantity = productInCart.cartItem.quantity;
qty = oldQuantity + 1;
return productInCart;
}
//console.log(Product.findByPk(prodId));
return Product.findByPk(prodId);
})
.then(product => {
console.log('product',product);
return fetchedCart.addProduct(product, {
through: { quantity: qty }
});
})
.then(() => {
res.redirect('/cart');
})
.catch(err => {
console.log(err);
})
};
Problem is that whenever I try to add a particular product to cart ,I end up with this error. I can see solutions to a lot of similar usecases here,but not related to the problem that I am facing at the moment.
Error Stack Trace.
Executing (default): SELECT `id`, `quantity`, `createdAt`, `updatedAt`, `cartId`, `productId` FROM
`cartItems` AS `cartItem` WHERE `cartItem`.`cartId` = 1 AND `cartItem`.`productId` IN ('[object SequelizeInstance:product]');
Executing (default): INSERT INTO `cartItems` (`id`,`quantity`,`createdAt`,`updatedAt`,`cartId`,`productId`) VALUES (NULL,1,'2020-02-22 07:39:45','2020-02-22 07:39:45',1,'[object SequelizeInstance:product]');
DatabaseError [SequelizeDatabaseError]: Incorrect integer value: '[object SequelizeInstance:product]'
for column 'productId' at row 1 at Query.formatError (C:\Users\Aravind\Documents\workspace-VSC\node_modules\sequelize\lib\dialects\mysql\query.js:244:16)
at Query.handler [as onResult] (C:\Users\Aravind\Documents\workspace-VSC\node_modules\sequelize\lib\dialects\mysql\query.js:51:23)
at Query.execute (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\commands\command.js:30:14)
at Connection.handlePacket (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:417:32)
at PacketParser.onPacket (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:75:12)
at PacketParser.executeStart (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:82:25)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
name: 'SequelizeDatabaseError',
parent: Error: Incorrect integer value: '[object SequelizeInstance:product]' for column 'productId' at row 1
at Packet.asError (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\packets\packet.js:712:17)
at Query.execute (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\commands\command.js:28:26)
at Connection.handlePacket (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:417:32)
at PacketParser.onPacket (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:75:12)
at PacketParser.executeStart (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:82:25)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
code: 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD',
errno: 1366,
sqlState: 'HY000',
sqlMessage: "Incorrect integer value: '[object SequelizeInstance:product]' for column 'productId' at row 1",
sql: "INSERT INTO `cartItems` (`id`,`quantity`,`createdAt`,`updatedAt`,`cartId`,`productId`) VALUES (NULL,1,'2020-02-22 07:39:45','2020-02-22 07:39:45',1,'[object SequelizeInstance:product]');",
parameters: undefined
},
original: Error: Incorrect integer value: '[object SequelizeInstance:product]' for column 'productId' at row 1
at Packet.asError (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\packets\packet.js:712:17)
at Query.execute (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\commands\command.js:28:26)
at Connection.handlePacket (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:417:32)
at PacketParser.onPacket (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:75:12)
at PacketParser.executeStart (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\packet_parser.js:75:16)
at Socket.<anonymous> (C:\Users\Aravind\Documents\workspace-VSC\node_modules\mysql2\lib\connection.js:82:25)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
code: 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD',
errno: 1366,
sqlState: 'HY000',
sqlMessage: "Incorrect integer value: '[object SequelizeInstance:product]' for column 'productId' at row 1",
sql: "INSERT INTO `cartItems` (`id`,`quantity`,`createdAt`,`updatedAt`,`cartId`,`productId`) VALUES (NULL,1,'2020-02-22 07:39:45','2020-02-22 07:39:45',1,'[object SequelizeInstance:product]');",
parameters: undefined
},
sql: "INSERT INTO `cartItems` (`id`,`quantity`,`createdAt`,`updatedAt`,`cartId`,`productId`) VALUES (NULL,1,'2020-02-22 07:39:45','2020-02-22 07:39:45',1,'[object SequelizeInstance:product]');",
parameters: undefined
}
Can someone please tell me what wrong I am doing here. I am able to console.log() the value of product as follows, which I think is correct.
product product {
dataValues: {
id: 1,
title: "Children's book",
price: 20,
imageUrl: 'orth-dakota-sunflower.jpg',
description: 'https://dynai5135742-02-n',
createdAt: 2020-02-22T10:05:22.000Z,
updatedAt: 2020-02-22T10:05:22.000Z
},
_previousDataValues: {
id: 1,
title: "Children's book",
price: 20,
imageUrl: 'orth-dakota-sunflower.jpg',
description: 'https://dynai5135742-02-n',
createdAt: 2020-02-22T10:05:22.000Z,
updatedAt: 2020-02-22T10:05:22.000Z
},
_changed: {},
_modelOptions: {
timestamps: true,
validate: {},
freezeTableName: false,
underscored: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: { id: '1' },
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'products', singular: 'product' },
omitNull: false,
sequelize: Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: {}
},
hooks: {}
},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [
'id',
'title',
'price',
'imageUrl',
'description',
'createdAt',
'updatedAt'
]
},
isNewRecord: false
}
Thanks in advance.