File size: 2,678 Bytes
c2efbe6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | const ProductModel = require('../models/productModel');
exports.getProducts = async (req, res, next) => {
try {
let query = {};
if (req.query.keyword) {
query.name = {
$regex: req.query.keyword,
$options: 'i'
};
}
if (req.query.category) {
query.category = req.query.category;
}
if (req.query.trending === 'true') {
query.ratings = { $gte: 4.0 };
}
if (req.query.minPrice || req.query.maxPrice) {
query.price = {};
if (req.query.minPrice) query.price.$gte = parseFloat(req.query.minPrice);
if (req.query.maxPrice) query.price.$lte = parseFloat(req.query.maxPrice);
}
const products = await ProductModel.find(query);
res.json({
success: true,
products
});
} catch (error) {
res.status(500).json({
success: false,
message: 'Unable to get products',
error: error.message
});
}
}
exports.getSingleProduct = async (req, res, next) => {
try {
const product = await ProductModel.findById(req.params.id);
res.json({
success: true,
product
})
} catch (error) {
res.status(404).json({
success: false,
message: 'Unable to get Product with that ID'
})
}
}
exports.getRecommendedProducts = async (req, res, next) => {
try {
const products = await ProductModel.aggregate([
{ $sample: { size: 8 } }
]);
res.json({
success: true,
products
})
} catch (error) {
res.status(500).json({
success: false,
message: 'Unable to get recommended products'
})
}
}
exports.getRelatedProducts = async (req, res, next) => {
try {
const { productId } = req.params;
const product = await ProductModel.findById(productId);
if (!product) {
return res.status(404).json({
success: false,
message: 'Product not found'
});
}
const relatedProducts = await ProductModel.find({
category: product.category,
_id: { $ne: productId }
}).limit(4);
res.json({
success: true,
products: relatedProducts
})
} catch (error) {
res.status(500).json({
success: false,
message: 'Unable to get related products'
})
}
} |