I want to display user scores ordered by scores:
const gotHighscore = {
score: req.body.score,
name: req.body.name,
created: new Date()
};
I start off with this in my server.js file:
app.get("/getHighscore", (req, res) => {
gotHighscore
.find()
.then(gotHighscore => {
res.json(gotHighscore);
});
});
Chrome log:
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...
The only way of sorting, that does not break everything and seemed easy to implement, looks like this:
app.get("/getHighscore", (req, res) => {
gotHigscore
.find({}, {sort : {score: -1}})
.then(gotHighscore => {
res.json(gotHighscore);
});
});
However, it does not order them how you would want it. It seems to me that it orders by the first digit and then second digit, not the value of the integer:
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...
Any ideas?
Thank you.
Save
scoreasnumber, not asstringso sorting will be by number and not by characters.Make sure
scoreis being saved asnumber, number values don have quotes{"number" : 5, "string": "string value"}.Try with:
and make sure this object generates: