Confusion with using Javascript callbacks or arrow functions to sort a NeDB database in a Get response

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.

Answer №1

To organize the data by timestamp, you can use the following code snippet:

collection.getData({}).sortBy({"timestamp":-1}).execute(function(error, result) {
    if (error) {
        reply.end();
        return;
    }
    console.info(result);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement authentication verification on all child endpoints within an express router

I have an express router set up and I want only authorized users to access its routes. I am currently using passport middleware. Instead of adding a check for req.user in every endpoint, is there a more efficient way to handle this? router.get("/", asyn ...

Utilizing AngularJS to calculate elapsed time and continuously update model and view accordingly

Situation Currently, I am interested in developing a web application that tracks a specific data set based on the time since the page was loaded. For example, "how many calories have you burned since opening this webpage?" I am still trying to grasp the ...

Updating div content dynamically with Jquery and PHP variable

How can I continuously update a div with the current date and time using PHP variable and Jquery? Here is my PHP file containing the variable date: <?php $date = date('d/m/Y H:i:s'); ?> And here's the code in my HTML file: <!DOCT ...

Image not yet clicked on the first try

I am encountering an issue with my image gallery. Currently, when I click on a thumbnail, the large image is displayed. However, I would like the first image to show up without requiring the user to click on its thumbnail. How can I address this problem? B ...

Creating smooth animations in JavaScript without relying on external libraries such as jQuery

Is there a way in JavaScript to make a <div> slide in from the right when hovered over, without relying on jQuery or other libraries? I'm looking for a modern browser-friendly solution. const div = document.querySelector('.fro ...

Mastering Array Dispatch in VueJS

I've encountered an issue while trying to send an array of data to the backend. I attempted to include [] in the dispatch variables and on the backend, but it only captures the last data sent to the backend. My objective is to associate each data with ...

Form validation is an essential feature of the Angular2 template-driven sub form component

I'm currently working on a template-driven form that includes a group of inputs generated through an ngFor. My goal is to separate this repeating 'sub-group' into its own child component. However, I'm encountering difficulties in ensur ...

Encountered an uncaughtException in Node.js and mongoDB: User model cannot be overwritten once compiled

Currently, I am utilizing this import statement const User = require("./Usermodel")' However, I would like to modify it to const User = require("./UserModel") Despite my efforts to align the spelling of the import with my other i ...

The ng-click function ceases to trigger after the $location dependency is included in the controller

I need some help with running a ng-click function from my controller. The strange thing is, when I don't use the $location dependency, the ng-click function works fine. But as soon as I add $location to the controller, the ng-click function stops work ...

Innovative and interactive animated data display

I've taken inspiration from an example and expanded the code to achieve the following: Dynamic height adjustment Accessibility without JavaScript enabled Is this implementation correct? Can it be expected to function properly on most browsers? You ...

Using jQuery to select a specific checkbox from a group of checkboxes with identical IDs

There is an issue with multiple checkboxes having the same ID in an asp.net repeater control. Users can select either email or phone against each record in the repeater rows. In the example below, there are two rows. If you select the email icon in the fi ...

Encountering difficulty accessing the router during testing in Next.js

Hello, I'm currently attempting to test a scenario where when a button is pressed, it should redirect to '/'. Normally this works fine, but during testing it fails and shows the following error: Cannot read properties of null (reading ' ...

How can I run an ajax request in a loop where it only proceeds to the next loop value upon successful completion?

I'm facing a simple but important issue: running 3 Google Maps place URLs and displaying the results after each one is successful. Here's my current approach: var values = ["url1", "url2", "url3"]; values.forEach(function(value, i) { var ...

Selenium unfortunately does not fully function with JavascriptExecutor

When I attempt to input text using JavascriptExecutor, the code snippet below is what I use: private void inputWorkDescription(WebDriver driver, int rawNumber) throws IOException, GeneralSecurityException { if (!getWorkDescriptionFromSheets(rawNum ...

Experiencing unexpected output from Angular model class method

I have developed a user-friendly Invoicing & Inventory management application that showcases a list of invoices for each customer. However, there seems to be an issue with the calculation of the Grand Total function, which I am struggling to rectify due to ...

What steps should I take to fix a critical SQL statement error?

After encountering difficulties updating information in my SQL database using my vb.net application, I was able to resolve the issue. However, I am now facing a new problem which is reflected in the code snippet below: Private Sub cmdupdate_Click(ByVal s ...

Storing the result of parsing JSON data into a global variable

$(function() { var countFromData = 0; getReminder(); alert(countFromData); }); function getReminder() { $.getJSON("<?=base_url()?>home/leavereminder", {}, function(data) { ...

Is it advisable to modify the value of props by using toRef in the Composition API?

I've noticed a common practice in the CompositionAPI where props are converted to refs using `toRefs` function. This has left me feeling a bit confused. For instance, citing the Vue 3 official guide: export default { props: { user: { type ...

Is there an obstacle hindering the load event?

There's something strange happening on a website I created. The page content loads in 5 or 6 seconds, but the DOMContentLoaded and Load Event don't actually fire until 1 minute and 10 seconds later. When I reload the page during loading, it load ...

Open multiple accordion sections simultaneously

In my current setup, I have a paginated loop of elements that contains an accordion. The accordion is implemented using angular-ui-bootstrap. <div data-ng-repeat="m in results"> <div class="stuff_in_the_middle"> <accordion id="a ...