When making an ajax call, I pass the object below to Mongoose:
{category: 'name', direction: 1}
To sort the query results using Mongoose, I use the following code:
Site.find(query).sort(sortBy)
Prior to this call, I need to format the object from the ajax request correctly and insert it into the query. Here's how I do it:
let sortBy = {};
let tmp = req.query['sortBy'];
sortBy.category = tmp["category"];
sortBy.direction = tmp["direction"];
Unfortunately, I encounter this error:
TypeError: Cannot read property 'toString' of undefined
When I log tmp to the console, I see:
tmp {"category":"name","direction":1}
However, when I log tmp["category"] and tmp["direction"], I get:
undefined undefined
Why am I unable to parse the strings into object keys?
UPDATE:
The workaround below works fine, but I'm still puzzled about why the initial code doesn't work:
var tmp = {};
var sortBy = {};
Object.keys(req.query).map(prop => {
if (prop === 'direction') {
tmp[prop] = parseInt(req.query[prop]);
} else if (prop === 'category') {
tmp[prop] = req.query[prop]
}
});
sortBy = {[tmp.category]: tmp.direction};
Why do I require this tmp object?