Mongoose传递嵌套排序对象进行查询

时间:2016-09-07 20:00:31

标签: arrays node.js mongodb sorting mongoose

我有以下查询,作为硬编码字符串传递:

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 );
} );

然而,当我尝试传递我的路线参数:round时,这样:

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

它不起作用(它返回一个未排序的列表)。

我也尝试过:

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

再次,没有成功。这是我正在查询的示例文档:

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

...我试图通过r(圆形)分数返回排序列表。

1 个答案:

答案 0 :(得分:1)

我认为这应该有效。

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

它只是javascript,默认情况下javascript中的对象键被转换为字符串

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}

在javascript对象中执行动态键,只需用括号

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