I am facing an issue with sorting the results from my NeDB database in my express server. Currently, when I retrieve the whole database, the order of results does not match the database file. I want to sort the results based on one of the timestamps in the database.
The structure of my database looks like this:
...
{"lat":1,"lon":7,"timestamp":1585781054239,"_id":"3cZvJfQyLEXK0SZo","createdAt":{"$$date":1585781054240},"updatedAt":{"$$date":1585781054240}}
{"lat":1,"lon":2,"timestamp":1585781047536,"_id":"DN9bpd1FygEowgtc","createdAt":{"$$date":1585781047538},"updatedAt":{"$$date":1585781047538}}
{"lat":1,"lon":6,"timestamp":1585781052398,"_id":"Dzp6x0xo3QM960Rm","createdAt":{"$$date":1585781052400},"updatedAt":{"$$date":1585781052400}}
{"lat":1,"lon":5,"timestamp":1585781051174,"_id":"KswtMYzV2QBE3xkb","createdAt":{"$$date":1585781051176},"updatedAt":{"$$date":1585781051176}}
...
I have attempted to add a sorting function to my code, but it resulted in a 500 GET error to the client and "TypeError: Cannot read property 'sort' of undefined" on the server. Here is the snippet of the code I tried:
app.get('/api', (request, response) => {
//query the database for everything
db
.find({}, (error, data) => {
if (error) {
response.end();
console.log(error)
return;
}
// console.log(data)
// response.json(data)
})
.sort({ createdAt: -1 }, (data) => {
console.log(data)
response.json(data)
});
});
I suspect that the sorting function should be nested within the .find() method, but I'm struggling with understanding the syntax properly. I have researched examples of sorting but couldn't find a solution that fits my current code structure.