J'écrirais fortement plus propre, ci-dessous l'exemple utilise async.parallel
, Promesse et Mongoose.Query
function list(req) {
// promise or callback works as well
return new Promise(function(resolve, reject){
// npm install async --save
var async = require('async');
// some validation can be applied
var page = {
skip: req.query.start || 1,
limit: req.query.length || 25,
text: req.query.search || '' // <== this is new property!
};
// reuse Mongoose.Query with search by regex
var Query = Models.SaleModel.find({
product_name: new RegExp(page.text, "i")
});
// run without waiting until the previous function has completed
async.parallel([
function(){
Query.count(callback); // <== count
},
function(){
Query.skip(page.skip).limit(page.limit).exec('find', callback); // <== items
// or the below one should also work, just don't remember
// Query.skip(page.skip).limit(page.limit).exec(callback);
}
]), function(err, results){
if(err){
reject(err);
} else {
resolve({
count: results[0],
data: results[1]
});
}
});
});
}