Untitled
unknown
plain_text
5 months ago
2.5 kB
3
Indexable
exports.viewProduct = catchAsync(async (req, res, next) => { const productId = req.params.id; let data = {}; let count = null // Validate the productId if (!isValidObjectId(productId)) { return res.status(400).json({ message: 'Invalid product ID' }); } const pathsAndFields = [ { path: 'subcategories', select: 'subcategory' }, { path: 'categories', select: 'category' }, { path: 'groups', select: 'group' }, { path: 'brand', select: 'brand' }, { path: 'offer', select: ['discount', 'status'] } ]; // .populate(pathsAndFields).exec(); const product = await Product.findById(productId).populate(pathsAndFields); if (!product) { return next(new AppError('product not found', 400)); } if (product.isvariant == true) { const attributes = await VariantAttribute.find({ product: product._id }); if (attributes.length < 1) { return next(new AppError('invalid visibility value', 400)); } count = 3 for (let prodvar_id of product.variants) { const prod = await ProductVariant.findById(prodvar_id).populate({ path: 'attributevalues', populate: { path: 'attribute' } }); let obj = data; for (let i = 0; i < attributes.length; i++) { for (let k = 0; k < prod.attributevalues.length; k++) { if (String(attributes[i]._id) == String(prod.attributevalues[k].attribute._id)) { if (obj.id) { if (!obj.values[prod.attributevalues[k].value.toString()]) { obj.values[prod.attributevalues[k].value.toString()] = {}; } } else { obj.id = prod.attributevalues[k].attribute._id; obj.name = prod.attributevalues[k].attribute.attributeName; obj.values = {}; obj.values[prod.attributevalues[k].value.toString()] = {}; } if (i == attributes.length - 1) { obj.values[prod.attributevalues[k].value.toString()] = {}; obj.values[prod.attributevalues[k].value.toString()] = prod; } else { obj = obj.values[prod.attributevalues[k].value.toString()]; } } } } } } const result = {}; result.product = product; if (product.isvariant == true) { result.variant = data; result.count = count; } res.status(200).json({ message: 'Product fetched successfully', data: result }); });
Editor is loading...
Leave a Comment