简体   繁体   English

如何在Mongoose上使用变量而不是字符串按数组索引排序?

[英]How to sort by Array index on Mongoose using a variable instead of string?

I'm trying to sort my data based on the index value of a variable. 我正在尝试根据变量的索引值对数据进行排序。

I want to have totalClicks[0] , but the totalClicks[0] syntax don't work. 我想拥有totalClicks[0] ,但是totalClicks[0]语法不起作用。 I've searched and tried using 'totalClicks.0' , which works fine. 我已经搜索并尝试使用'totalClicks.0' ,效果很好。 But I need to check the req.params.bossId to sort the data based on the array[req.params.bossId] . 但是我需要检查req.params.bossId以基于array[req.params.bossId]对数据进行排序。

This first , hardcoded, code works. 这第一个经过硬编码的代码有效。

User.find({}).sort({ 'totalClicks.0' : '1'}).exec(
  function (err, data) {
    res.json(data);
});

This code , which dynamically selects which array field to sort, don't work and the whole .sort method gets ignored. 该代码动态选择要排序的数组字段,但不起作用,整个.sort方法将被忽略。

var bossId = req.params.bossId;
var totalClicksId = 'totalClicks.' + bossId;

console.log(totalClicksId);           // totalClicks.0
console.log(typeof(totalClicksId));   // string

User.find({}).sort({ totalClicksId : '1'}).exec(
  function (err, data) {
    res.json(data);
  });

If the ID variable is 0 , them I want to sort the data by totalClicks[0] . 如果ID变量为0 ,则我想通过totalClicks[0]对数据进行排序。
If the ID variable is 1 , them I want to sort the data by totalClicks[1] . 如果ID变量为1 ,则我想通过totalClicks[1]对数据进行排序。

I need to receive a variable bossId and, using that variable, sort my data based on the array[bossId] . 我需要接收一个变量bossId并使用该变量根据array[bossId]对我的数据进行排序。 How could I do that? 我该怎么办?

Appendix: 附录:

Model: 模型:

[
  {
    "username": "p",
    "totalClicks": [
      67,
      25
    ]
  },
  {
    "username": "kk",
    "totalClicks": [
      61,
      38
    ]
  }
]

You can't set an objects keys with a variable containing a string literally like that, and your sort function basically takes an object as it's argument. 您不能使用包含像这样的字面量的字符串的变量来设置对象键,并且您的sort函数基本上将对象作为参数。

.sort({key : value})

to create an object with dynamic keys, we have to do 用动态键创建一个对象,我们要做

var obj = {};
var key = 'something';

obj[key] = 'value'; // now obj === {'something' : 'value'}

So the solution is to create the object first, then pass it in 因此解决方案是先创建对象,然后将其传递

var totalClicksId = 'totalClicks.' + req.params.bossId;

var obj = {};

obj[totalClicksId] = '1';

User.find({}).sort(obj).exec(function (err, data) {
   res.json(data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM