I am trying to build backend for my cart with node.I want to create API's for the cart that adds product and increase quantity if the product id is same but can't figure out how to do this. Thank you all in advance for helping me out.
This is my model:
module.exports = (mongoose) =>
new mongoose.Schema(
{
userId: { type: Number, required: true, unique: true },
product: {
productId: { type: Number, required: true },
slug: { type: String, required: true },
name: { type: String, required: true },
image: { type: String, required: true },
},
options: [
{
optionId: { type: Number, required: true },
optionTitle: { type: String, required: true },
valueId: { type: Number, required: true },
valueTitle: { type: String, required: true },
},
],
price: { type: Number, required: true },
quantity: { type: Number, required: true, min: 1 },
},
{ timestamps: true }
);
and this is my service method: In this method what can I do to increase the quantity rather than adding the same product again?
const db = require('../models');
const logger = require('../utils/logger');
const service = 'cart';
const tag = service + '.js';
module.exports = {
addItem: async (payload, auth) => {
try {
const cartExist = await db.Cart.findOne({
userId: auth.credentials.customerId,
});
if (!cartExist) {
const cart = {
userId: auth.credentials.customerId,
product: payload.product,
options: payload.options,
price: payload.price,
quantity: payload.quantity,
};
await db.Cart.create(cart);
return { success: true, data: cart };
} else {
console.log('Quantity increased');
}
} catch (error) {
logger.error(tag + ': add', error);
return { success: false, data: error };
}
},
};