I have an express server and a simple NeDB database. I can successfully get the whole database like so:
app.get('/api', (request, response) => {
//queuery the database for everything
db
.find({}, (error, data) => {
if (error) {
response.end();
console.log(error)
return;
}
console.log(data)
response.json(data)
})
But I noticed the results are, for some reason, not the same order as the database file. I want to sort by one of the timestamps. The database looks like:
...
{"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 admittedly haven't quite wrapped my head around how the callbacks work in this code. I have tried something like the following but it returns a 500 GET error to the client and returns "TypeError: Cannot read property 'sort' of undefined" to the server:
app.get('/api', (request, response) => {
//queuery 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 wonder if it should be nested in the .find() function but at this point I'm quite in over my head and I believe I'm just not understanding the syntax. I have found examples of sorting but not in this context.