英文:
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) {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论