MongoDB排序文档不起作用,尝试对数据进行排序。

huangapple go评论65阅读模式
英文:

Mongo db Sort document not working, trying to order 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 
英文:

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

答案1

得分: 0

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

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) {}
英文:

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

huangapple
  • 本文由 发表于 2023年1月10日 15:22:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75066684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定