1

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.

1 Answer 1

2

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; //{ String("score.0.r" + req.params.round) : -1} 
       //{ '"score.0.r" + req.params.round': -1}

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

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
Sign up to request clarification or add additional context in comments.

1 Comment

Genius! Thank you, I would never have thought of that. If you'd like to provide a short explanation with this I am sure it will be very useful for others too. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.