I want to sort a mongo collection on base of following query in URL string from a node application.
http://localhost:5000/v1/bid/sort_bid?sort={"_id": -1,"enquiry_no": 1}
how do I pass an object in following code?
const getSortedBidList = catchAsync(async (req, res) => {
let { sort } = req?.query;
console.log('Query String', sort);
let object = new Object();
object[sort] === 1 ? 'ASC' : 'DESC';
let result = await Bid
.find({})
.sort(object)
.limit(limit)
.skip(offset);
} In the sort method I am passing object of query string, but it didn't work. Please help to sort this out. Thank You
Try the following:
http://localhost:5000/v1/bid/sort_bid?sort[_id]=-1&sort[enquiry_no]=1
Learn more about how express parses query strings from here.
I recommend that you use npm qs package to parse the objects on your frontend into query strings programatically:
import qs from 'qs';
async function sendRequestToBackend(queryAsObject) {
const stringifiedQuery = qs.stringify(queryAsObject);
await sendRequest(`http://localhost:5000/v1/bid/sort_bid?${stringifiedQuery}`)
}