Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongo db Sort document not working, trying to order data

I’m trying to sort data

try{
  if(typeof order_data == 'undefined')
{
    var column_name = '_id';

    var column_sort_order = 'desc';
}
else
{
    
    var column_index = req.query.order[0]['column'];

    var column_name = req.query.columns[column_index]['data'];

    var column_sort_order = req.query.order[0]['dir'];
}
console.log(column_name);
console.log(column_sort_order);

const data_arr= await EAVerificationModel.find({'adminid':adminID},{applicantname:1,_id:1}).sort({column_name:column_sort_order}).limit(limit).skip(startIndex).exec();
console.log(data_arr);

tried different different methods like asc,desc,1,-1 still didnt work,
can anyone tell me what im doing wrong

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try to create an object to handle your sorting:

try {
  let sortObj = {};
  if (order_data) {
    const column_index = req.query.order[0]['column'];
    const column_name = req.query.columns[column_index]['data'];
    const column_sort_order = req.query.order[0]['dir'];
    sortObj[column_name] = column_sort_order;
  } else {
    sortObj = { _id: 'desc' };
  }

  const data_arr = await EAVerificationModel.find(
    { adminid: adminID },
    { applicantname: 1, _id: 1 }
  )
    .sort(sortObj)
    .limit(limit)
    .skip(startIndex)
    .exec();
  console.log(data_arr);
} catch (e) {}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading