lechnerio
lechnerio

Reputation: 980

Mongoose, NodeJS & Express: Sorting by column given by api call

I'm currently writing a small API for a cooking app. I have a Recipe model and would like to implement sorting by columns based on the req Parameter given.

I'd like to sort by whatever is passed in the api call. the select parameter works perfectly fine, I can select the columns to be displayed but when I try to sort anything (let's say by rating) the return does sort but I'm not sure what it does sort by.

The code i'm using:

query = Recipe.find(JSON.parse(queryStr));

if(req.query.select){
    const fields = req.query.select.split(',').join(' ');
    query = query.select(fields);
}

if(req.query.sort){
    const sortBy = req.query.sort.split(',').join(' ');
    query = query.sort({ sortBy: 1 });
} else {
    query = query.sort({ _id: -1 });
}

The result, when no sorting is set: https://pastebin.com/rPLv8n5s

vs. the result when I pass &sort=rating: https://pastebin.com/7eYwAvQf

also, when sorting my name the result is also mixed up.

Upvotes: 1

Views: 1069

Answers (1)

Daniel
Daniel

Reputation: 2531

You are not using the value of sortBy but the string "sortBy". You will need to create an object that has the rating as an object key.

You need the sorting object to look like this.

{
   rating: 1
}

You can use something like this so it will be dynamic.

if(req.query.sort){
    const sortByKey = req.query.sort.split(',').join(' ');
    const sortByObj = {};
    sortByObj[sortByKey] = 1; // <-- using sortBy as the key
    query = query.sort(sortByObj);
} else {
    query = query.sort({ _id: -1 });
}

Upvotes: 1

Related Questions