【发布时间】:2021-12-05 21:48:54
【问题描述】:
我正在尝试使用 node 为我的购物车构建后端。如果产品 ID 相同,我想为购物车创建 API 以添加产品并增加数量,但不知道如何执行此操作。 提前感谢大家帮助我。
这是我的模型:
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 }
);
这是我的服务方法: 在这种方法中,我可以做些什么来增加数量而不是再次添加相同的产品?
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 };
}
},
};
【问题讨论】:
标签: node.js mongodb mongoose hapi