Matt Webb Matt Webb - 2 months ago 5
Node.js Question

Mongoose pass nested sort object to query

I have the following query which, passed as a hard coded string works:

router.get( '/rank/:round/', ( req, res, next ) => {

let query = { "score.0.r1" : -1};

Team.find( {} )
.sort( query )
.then( teams => {
return res.json( teams );
} ).catch( next );
} );


However, when I try to pass in my route param
:round
like this:

let query = { "score.0.r" + req.params.round : -1};


It doesn't work (it returns an unsorted list).

I have also tried:

let sort = "score.0['r" + req.params.round + "']";
let query = { sort : -1 };


Again, with no success. Here is my an example document I am querying:

{
"_id" : ObjectId("57cc7665a43bf14533b0d78a"),
"name" : “Joe Bloggs”,
"score" : [
{
"r5" : 23,
"r4" : 20,
"r3" : 25,
"r2" : 23,
"r1" : 40
}
]
}


... where I am trying to return a sorted list by r (round) score.

Answer

I think this should work.

let sort =  "score.0.r" + req.params.round
let query = { [sort] : -1 };

It's just javascript, by default object's key in javascript is converted to a string

let query = { "score.0.r" + req.params.round : -1};
query; //{'"score.0.r" + req.params.round' : -1} => the key is a string with single quote

let sort = "score.0['r" + req.params.round + "']";
let query = { sort : -1 };
query; // {"sort" : -1} => key is "sort":String

to do dynamic key in javascript object, just enclose the key with bracket

var string = "any_string" + variable
var obj = { [string] : "anyvalue"} 
//this will tell javascript that the key is variable not a string
Comments