Is it possible to organize MongoDB records that possess identical update timestamps?

My goal is to validate a route within my Express server using Supertest. This particular route retrieves data from a MongoDB, and the data is then sorted based on the updatedAt field.

While attempting to test the order of the output, I encountered an issue - it appears that some documents in the MongoDB have identical timestamps (which came as quite a surprise).

https://i.sstatic.net/eg9t3.jpg

How exactly is this sorting happening internally? It doesn't seem to be sorted by _id either. Here's the function from my test that generates these documents:

let first;
let last;
Array.from(Array(14)).forEach((e, i) => {
  const immo = new Immo({ user: this.user.model });
  immo.save();
  if (i === 2) {
    // identifying the last document with limit 12 sorted by descending timestamps
    last = immo._id.toString();
  }
  if (i === 13) {
    // marking the most recent document, which should appear first in the sorted list
    first = immo._id.toString();
  }
});

The resulting output comprises the last 12 items edited by the user. I store references to the earliest and latest documents for later assertion purposes.

However, the test fails due to several documents sharing the same timestamp, causing incorrect ordering. The document that was inserted last in the DB isn't necessarily appearing last when Mongo sorts by timestamps.

I even attempted introducing a delay within a for-loop during the input process, but it had no effect. (Is there a better alternative than using Array.forEach?)

Is there a way to ensure a minimum time gap between the documents to overcome this issue?

Answer №1

After realizing the issue, I discovered that neglecting the asynchronous nature of processes was causing my problem.

To resolve it, I encapsulated everything in Promises, which successfully resolved the issue. Below is the updated code:

it('should return a list of the last 12 objects if a user has 14 objects', function (done) {
    let first;
    let last;
    let i = 0;
    const model = this.user.model;
    (function recur() {
      i += 1;
      return new Immo({ user: model })
        .save()
        .then((result) => {
          if (i === 3) {
            last = result._id.toString();
          } else if (i === 14) {
            first = result._id.toString();
          }
          if (i >= 14) {
            return result;
          }
          return recur();
        });
    }())
    .then(() => {
      this.request(this.app)
        .get(url)
        .set('Authorization', this.authHeader)
        .expect(200)
        .end((err, res) => {
          if (err) {
            done.fail(err.message);
          } else {
            expect(res.body.count).toBe(14);
            expect(res.body.objects.length).toBe(12);
            expect(res.body.objects[0]._id).toEqual(first);
            expect(res.body.objects[11]._id).toEqual(last);
            done();
          }
        });
    });

I'm uncertain if this solution will be compatible with versions below ES2015 due to recursion using generating functions.

When Mongoose started giving errors with its own Promises, I included the following line on top of my test-setup function:

const mongoose = require('mongoose');
mongoose.Promise = require('q').Promise;

Although it took up a significant amount of time, I believe it was worth it to overcome this particular challenge! :D

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

The sorting icon in jQuery Data Table's search option is not functioning

I am having an issue with jQuery DataTables. When using jQuery DataTables, it provides a default search option. However, the problem arises when I search for a particular record and if the content does not match or if I find a single record, then I need to ...

Aligning text to the right in Bootstrap 5 input fields

I'm trying to align the values of my inputs to the right. Any suggestions on how to achieve this? Here's a visual representation of what I'm looking for. This is the snippet from my code: <td style="text-align:center; vertical-alig ...

Ways to update all URLs on a page with ajax functionality

My userscript is designed to modify the href of specific links on an IP-direct Google search page: // ==UserScript== // @name _Modify select Google search links // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @include http://62.0.54.118/* // ==/Us ...

Looking to perform an Ajax call to update a Rails model using HTML5 contenteditable, but encountering an issue where it creates a new

I am in need of assistance to update the plots of a story using HTML5 contenteditable feature. Below is the code snippet: Refer to file# for editing multiple plots <div id="editable" contenteditable="true"> <%= simple_format p.description %&g ...

Display the URL with proper formatting in the print function

I am trying to create a table with clickable URLs in a "Link" column, but the URLs are too long and I want to show a custom title instead. So far, I have used the following code: str = "Test Title"; link = str.link("https://my_long_url.com/v1.0/ui/index. ...

Issues with jQuery requests not working properly on the mobile application

Creating a mobile application for Android devices using Intel XDK has been a rewarding experience so far. I have been testing my PHP code on an emulator and local development server (127.0.0.1) through AJAX methods such as $.ajax(), $.post(), and $.get(). ...

Tips for adjusting the size of a drawing on an HTML 5 canvas within a personalized Polymer component

In my custom Polymer element, I am looking to dynamically resize an html5 canvas when the window resize event occurs. Despite trying to utilize the window.onresize event, I encountered difficulties with accessing canvas functions. One of the functionalit ...

Can you explain the variances between ngx-translate and ngx-i18next for me?

As ngx-i18next serves as a wrapper for i18next, I am curious about the specific differences in translation capabilities between ngx-translate and i18next. ...

It appears that the pixel sizes are different than what was originally designed

In my project, I have a header panel where the burger button is designed with a width of 32px and height of 24px. .header { display: flex; font-weight: bold; font-size: 50px; height: 100px; border: 1px solid black; position: relativ ...

JavaScript not redirecting to HTML page as expected

I have developed a basic login page that makes an Ajax request to the backend. However, I am experiencing difficulties with redirecting the page upon successful login. The redirect function only seems to work 1 in 15 times, and I'm unsure of the reaso ...

What changes can I make to my mongodb/mongoose query in order to generate a more comprehensive JSON output?

Within my application, there exists a model dedicated to storing user data. Users have the ability to block other users, resulting in the creation of an entry within this model that incorporates the IDs of blocked users: ... blocked_user_ids: {type: [Stri ...

The function toggleClass() is malfunctioning

The .toggleClass() method seems to only be adding the "class" attribute to my selection, resulting in: <div id="toggle" class> ... rather than: <div id="toggle" class="on"> ... I've been trying to solve this issue for about 2 hours now ...

What is the significance of :: in AngularJS?

When reviewing certain Angular JS files, I often come across the following syntax. What is the significance of a double colon "::" in this context? <span>{{::x}}</span> <div>{{::y.z()}}</div> ...

In order to utilize the componentDidUpdate lifecycle method, I passed props to the Outlet component while nesting it

I am currently using react-router-v6 and encountering some issues with my configuration. I have implemented nested routing with layouts according to the following settings. App.js <BrowserRouter> <Routes> <Route exact pat ...

How can I create an asynchronous route in AngularJS?

I implemented route and ngView to display dynamic content, however I received a warning message: The use of Synchronous XMLHttpRequest on the main thread is deprecated due to its negative impact on user experience. For more assistance, please refer to ...

In JavaScript, private variables are not included in the JSON.stringify output

Imagine creating a class called Rectangle with private fields like width and height, initializing them in the constructor. However, when calling JSON.stringify on an instance of this class, it returns an empty object without including the private members. ...

Issue with receiving output from tessearct.js in PDF format

I am currently working on a basic javaScript OCR (Optical Character Recognition) application using tesseract.js. I have included {tess_create_pdf: "1"} in the .recognize() method to receive the result in PDF format, but it seems to be malfunctioning. Can ...

Gradebook modeling is an essential aspect of educational management

Currently, I am in the process of designing the database for my MERN application (which employs Next.js in addition to React.js). The main purpose of my app is to serve as an LMS (Learning Management System) where educators can post assignments, tests, r ...

The specified element type is not valid: only a string (for built-in components) or a class/function is expected when attempting to display a component

`Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you mi ...

Generating a request to API using Express and create-react-app

I have my create-react-app running on localhost:3000 with a proxy set up in package.json to point to my server running at localhost:3001. { "name": "my-app", "version": "0.1.0", "private": true, "dependencies": { "axios": "^0.18.0", "react ...