Untitled
unknown
plain_text
4 months ago
2.6 kB
4
Indexable
exports.searchGlobal = catchAsync(async (req, res, next) => { const { filter } = req.query; let { page, limit } = req.query; if (!filter) { return next(new AppError('filter is required', 400)); } page = page ? parseInt(page) : 1; limit = limit ? parseInt(limit) : 10; const results = await Product.aggregate([ { $match: { visibility: true } }, { $lookup: { from: 'categories', localField: 'categories', foreignField: '_id', as: 'categories' } }, { $lookup: { from: 'subcategories', localField: 'subcategories', foreignField: '_id', as: 'subcategories' } }, { $lookup: { from: 'groups', localField: 'groups', foreignField: '_id', as: 'groups' } }, { $lookup: { from: 'brands', localField: 'brand', foreignField: '_id', as: 'brand' } }, { $lookup: { from: 'offers', localField: 'offer', foreignField: '_id', pipeline: [{ $project: { discount: 1, status: 1 } }], as: 'offer' } } ]); const array = new Array(); for (let i = 0; i < results.length; i++) { array[i] = { name: { fr: results[i]?.name.fr, en: results[i]?.name.en }, categories: [], subcategories: [], groups: [], brand: [] }; for (let j = 0; j < results[i]?.categories.length; j++) { if (results[i]?.categories[j].category) { array[i].categories.push({ category: results[i]?.categories[j].category }); } } for (let j = 0; j < results[i]?.subcategories.length; j++) { array[i].subcategories[j] = { subcategory: results[i]?.subcategories[j].subcategory }; } for (let j = 0; j < results[i]?.groups.length; j++) { array[i].groups[j] = { group: results[i]?.groups[j].group }; } for (let j = 0; j < results[i]?.brand.length; j++) { array[i].brand[j] = { brand: results[i]?.brand[j].brand }; } } const fuse = new Fuse(array, fuseOptions); const lists = fuse.search(filter); let indexs = new Array(); for (const list of lists) { indexs.push(list.refIndex); } let ProductsList = indexs.map(function (item) { return results[item]; }); let products = ProductsList.slice((page - 1) * limit, page * limit); res.status(200).json({ products, count: products.length }); });
Editor is loading...
Leave a Comment