0

I want to pass this name variable in sort function. I am getting the value of name in console.log but its not working in sort function.

var coldata = req.body.order[0].column;
var name = req.body.columns[coldata].data; // Want to pass this variable in sort()
var first = req.body.order[0].dir;
var last = req.body.order[0].dir;
var x,y;
        if (first == 'asc'){
            x = 1
        }else{
            x = -1;
        }
        if (last == 'asc'){
            y = 1
        }else{
            y = -1;
        }

        var searchStr = req.body.search.value;
        if(req.body.search.value)
            {
                var regex = new RegExp(req.body.search.value, "i")
                searchStr = { $or: [{'firstname':regex },{'lastname': regex}] };
            }
         else
            {
                searchStr={};
            }
        console.log(req.body.search.value)
        var recordsTotal = 0;
        var recordsFiltered=0;
        console.log(searchStr); 
        db.count({}, function(err, c) {
            recordsTotal=c;
            db.count(searchStr, function(err, c) {
                recordsFiltered=c;
                db.find(searchStr, 'firstname lastname',{'skip': Number( req.body.start), 'limit': Number(req.body.length) }, function (err, results) {
                    if (err) {
                        console.log('error while getting results'+err);
                        return;
                    }
                    var data = JSON.stringify({
                        "draw": req.body.draw,
                        "recordsFiltered": recordsFiltered,
                        "recordsTotal": recordsTotal,
                        "data": results
                    });
                    res.send(data);
                }).sort({name:x});// Not getting value of name here 
          });
   });
});
Joe
  • 25,000
  • 3
  • 22
  • 44
  • Have you tried building the sort object like you did the search? Also see https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name – Joe Jan 18 '22 at 07:22

1 Answers1

0

You can use an aggregation pipeline

const sort = {};
sort[name] = x
const pipeline = [
    { $match: searchStr },
    { $skip: Number( req.body.start) },
    { $limit: Number( req.body.length) },
    { $sort: sort }
];

db.aggregate(pipeline) ...
Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110