74 lines
1.7 KiB
JavaScript
74 lines
1.7 KiB
JavaScript
|
|
||
|
const advancedResult =(model)=> async (req, res, next) => {
|
||
|
//search : l'information que je cherche
|
||
|
//fields : les colonnes je veux utiliser pour la recherche
|
||
|
const fields = req.query.fields;
|
||
|
const search = req.query.search;
|
||
|
let page = req.query.page;
|
||
|
let limit = req.query.limit;
|
||
|
|
||
|
|
||
|
let find = {}
|
||
|
//Recherche
|
||
|
if (fields) {
|
||
|
|
||
|
//Recherche l'element search dans le tableau de propriété fields
|
||
|
const query = {
|
||
|
$or: fields.map(property => ({
|
||
|
[property]: {$regex: search, $options: 'i'}
|
||
|
}))
|
||
|
};
|
||
|
|
||
|
find = {
|
||
|
$and: [
|
||
|
find,
|
||
|
query,
|
||
|
]
|
||
|
};
|
||
|
}
|
||
|
|
||
|
//Pagination
|
||
|
page = parseInt(page, 10) || 1;
|
||
|
limit = parseInt(limit, 10) || 3000;
|
||
|
const startIndex = (page - 1) * limit; //1, 1-1 = 0
|
||
|
const endIndex = page * limit;
|
||
|
const total = await model.find(find).countDocuments();
|
||
|
|
||
|
//declaration
|
||
|
let query = model.find(find);
|
||
|
|
||
|
query = query.skip(startIndex).limit(limit); // (5,8) 5,6,7,8,9,10,11, 12
|
||
|
|
||
|
//exécuté
|
||
|
let results = await query;
|
||
|
const pagination = {};
|
||
|
|
||
|
if (endIndex < total) {
|
||
|
pagination.next = {
|
||
|
page: page + 1,
|
||
|
limit
|
||
|
};
|
||
|
}
|
||
|
|
||
|
if (startIndex > 0) {
|
||
|
pagination.prev = {
|
||
|
page: page - 1,
|
||
|
limit
|
||
|
};
|
||
|
}
|
||
|
|
||
|
res.advancedResults = {
|
||
|
success: true,
|
||
|
count: results.length,
|
||
|
pagination: pagination,
|
||
|
data: results,
|
||
|
startIndex: startIndex + 1,
|
||
|
endIndex: results.length,
|
||
|
totalRecords: total,
|
||
|
limit: Number(limit),
|
||
|
page: page
|
||
|
};
|
||
|
next();
|
||
|
};
|
||
|
|
||
|
module.exports = advancedResult;
|