按数组中的最后一项排序

时间:2018-11-21 15:15:42

标签: node.js mongodb sorting mongoose

我正在尝试按数组中的最后一项对它进行排序。这样我就可以按最近的年份对这个人进行排序。

这是我用来返回结果的函数。

router.get('/', (req, res) => {
  const errors = {};
  Person
    .find()
    .limit(pagingLimit)
    .sort(
      {year:[0]}
    )
    .then(people => {
      if (!people) {
        errors.noprofile = 'There are no profiles';
        res.status(404).json(errors);
      }

      return res.json(people)
    })
    .catch(err => res.status(404).json({
        nopeoplefound: 'No people found'
    }));
});

这是我用来排序的项目的示例。

{
  "first_name": "James",
  "last_name": "Smith",
  "years": [
    {
      "year": 2016,
      "sector": "Produce",
      "job_title": "Coroner"
    },
    {
      "year": 2017,
      "sector": "Produce",
      "job_title": "Senior Coroner"
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

您可以$unwind年通过汇总,然后按years: -1排序:

Person.aggregate([
  { $unwind: "$years" },
  { $sort: { years: -1 }}
]).exec()
.then(result => ...)

查看working here