简体   繁体   中英

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. I've searched and tried using 'totalClicks.0' , which works fine. But I need to check the req.params.bossId to sort the data based on the 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.

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] .
If the ID variable is 1 , them I want to sort the data by totalClicks[1] .

I need to receive a variable bossId and, using that variable, sort my data based on the 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({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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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