首页 > 解决方案 > 如何正确将此请求排序到 mongodb?

问题描述

我想显示按分数排序的用户分数:

  const gotHighscore = {
    score: req.body.score,
    name: req.body.name,
    created: new Date() 
  };

我从我的 server.js 文件开始:

app.get("/getHighscore", (req, res) => {
  gotHighscore
      .find()
      .then(gotHighscore => {
        res.json(gotHighscore);
      });
});

铬日志:

0: {_id: "5e57afae67db842ff4bf806b", score: "150", name: "Hendel", created: "2020-02-27T12:01:50.173Z"}
1: {_id: "5e57b4fb67db842ff4bf806c", score: "70", name: "123", created: "2020-02-27T12:24:27.351Z"}
2: {_id: "5e57b63667db842ff4bf806d", score: "110", name: "iseemypee", created: "2020-02-27T12:29:42...

唯一的排序方式,不会破坏一切并且看起来很容易实现,如下所示:

app.get("/getHighscore", (req, res) => {
  gotHigscore
      .find({}, {sort : {score: -1}})
      .then(gotHighscore => {
        res.json(gotHighscore);
      });
});

但是,它并没有按照您的意愿对它们进行排序。在我看来,它是按第一个数字排序,然后是第二个数字,而不是整数的值:

0: {_id: "5e57b4fb67db842ff4bf806c", score: "70", name: "123", created: "2020-02-27T12:24:27.351Z"}
1: {_id: "5e57afae67db842ff4bf806b", score: "150", name: "Hendryk", created: "2020-02-27T12:01:50.173Z"}
2: {_id: "5e57b63667db842ff4bf806d", score: "110", name: "iseemypee", created: "2020-02-27T12:29:42.25...

有任何想法吗?

谢谢你。

标签: node.jsmongodbexpressmonk

解决方案


http 正文在保存到数据库时必须从字符串转换为整数,以便按整数值排序。

reg.body.score.toInt()没用(错误:不是函数),虽然我在其他地方看到过。使用 parseInt 为我解决了这个问题:

  const mew = {
    score: parseInt(req.body.score),
    name: req.body.name,
    created: new Date() 
  };

推荐阅读