NodeJS Mongo db排序文档不工作,尝试排序数据

cclgggtu  于 2023-01-12  发布在  Node.js
关注(0)|答案(1)|浏览(106)

我在整理数据

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);

我尝试了不同的方法,如asc,desc,1,-1仍然没有工作,谁能告诉我我做错了什么

iqjalb3h

iqjalb3h1#

尝试创建一个对象来处理排序:

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) {}

相关问题