node.js - 如何正确将此请求排序到 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...
有任何想法吗?
谢谢你。
解决方案
http 正文在保存到数据库时必须从字符串转换为整数,以便按整数值排序。
reg.body.score.toInt()
没用(错误:不是函数),虽然我在其他地方看到过。使用 parseInt 为我解决了这个问题:
const mew = {
score: parseInt(req.body.score),
name: req.body.name,
created: new Date()
};
推荐阅读
- python - 奇怪的行为:“12 in [12,13,14] == True”在 Python 中是什么意思
- c# - MSSQL 连接失败,登录凭据正确
- python - 在 Python 中使用 Selenium 时是否可以有多个显式等待?
- python - 使用beautifulsoup查找没有标签的json对象
- c++ - OpenSSL C API 解密有时不起作用
- c++ - 我必须在 C++ 的头文件中定义类吗?
- reactjs - 在 React 中创建共享身份验证 cookie
- python-3.x - ModuleNotFoundError:没有名为“tensorflow.experimental.numpy”的模块
- oracle - Oracle 数据库中的存储过程 (11g)
- django - Django:使用 sengrid 在电子邮件中添加 cc 返回 HTTP 错误 400:错误请求