Chaining updateMany() calls in MongoDB while ensuring synchronous response handling

I have encountered an issue while attempting to send 3 separate updateMany requests within a get request, each using a different query. While the first two requests work perfectly, the third updateMany request only functions as expected after refreshing the page twice.

Below is the code I am currently using:

app.get('/', (req, res) => {
         let todaysDate = new Date().toString().split(' ').slice(0, 4).join(' ')
         let todaysDateMs = new Date(todaysDate + ', 00:00:00').getTime()

         habitsCollection.updateMany({}, {
            $set: {
               todaysDate,
               todaysDateMs
            }
         }).then(res => {
            habitsCollection.updateMany({ lastClicked: { $ne: todaysDate } }, {
               $set: {
                  clicked: 'false'
               }
            }).then(res => {
               habitsCollection.updateMany({ $expr: { $gte: [{ $subtract: ["$todaysDateMs", "$lastClickedMs"] }, 172800000] } }, {
                  $set: {
                     streak: 0
                  },
               })
            })
         })

         habitsCollection.find({}).toArray()
            .then(results => {
               console.log(results)
               let filtered = results.filter(result => result.clicked === 'false')
               habitsLeft = filtered.length
               res.render('index.ejs', { habits: results, dayVar: 'days', habitsLeft })
            })
      })

My expectation was that on every page load, if a document contains a lastClickedMs key/value subtracted from todaysDateMs key/value which is greater than or equal to 172800000, then the streak value should be reset to 0. This functionality does occur but only after loading the page for the second time.

Answer №1

I believe the issue lies in not waiting for the promises to resolve before calling

habitsCollection.find({}).toArray()
. A solution would be to use Promise.all to manage multiple promises.

app.get('/', (req, res) => {
  let todaysDate = new Date().toString().split(' ').slice(0, 4).join(' ');
  let todaysDateMs = new Date(todaysDate + ', 00:00:00').getTime();

  Promise.all([
    habitsCollection.updateMany({}, {
      $set: {
        todaysDate,
        todaysDateMs
      }
    }),
    habitsCollection.updateMany({ lastClicked: { $ne: todaysDate } }, {
      $set: {
        clicked: 'false'
      }
    }),
    habitsCollection.updateMany({ $expr: { $gte: [{ $subtract: ["$todaysDateMs", "$lastClickedMs"] }, 172800000] } }, {
      $set: {
        streak: 0
      },
    })
  ]).then(() => {
    habitsCollection.find({}).toArray()
      .then(results => {
        console.log(results);
        let filtered = results.filter(result => result.clicked === 'false');
        habitsLeft = filtered.length;
        res.render('index.ejs', { habits: results, dayVar: 'days', habitsLeft });
      });
  });
});

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

Error encountered in pre-middleware hooks when querying Mongoose model with findById due to foreign model reference

Within this scenario, I have two distinct models: Protocol and Comment. Each model incorporates a middleware ('pre' or 'remove') that triggers the other model. The issue arises when attempting to call the Comment middleware in Comment.j ...

Tips for informing flowtype of expanding a partial options object to ensure it is fully developed by a specific stage

Most of you are probably familiar with a very simple use case from your projects. Imagine you have a utility class or function that looks like this: type Options = { foo?: string }; class Something { static get defaultOptions(): Options { ...

Discovering the difference between a singular array and an array of arrays

x = [1, 2,3, 5]; y = [1, [2], [3, [[4]]],[5,6]])); I am currently facing a challenge in finding the difference between these two arrays. function findArrayDifference(arr1, arr2) { var tempArr = [], difference = []; for (var i = 0; i < arr1.l ...

Can child components forward specific events to their parent component?

I created a basic component that triggers events whenever a button is clicked. InnerComponent.vue <template> <v-btn @click="emit('something-happened')">Click me</v-btn> </template> <script setup lang=" ...

Automatic logoff will occur after 15 minutes of inactivity in C# programming language

After a period of 15 minutes, the following method logs out the user. However, it currently logs out the user even if they are active. I am seeking a solution where the method will only log out the user if they have been inactive for the full 15 minutes. ...

Ways to extract the first name and email address from a JSON payload

{ "userID": 1, "userHandle": "username", "first_name": "firstname", "last_name": "lname", "middle_initial": null, "email_address": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e203d250e29232f27 ...

The change event for Bootstrap 4 switches is not functioning as expected

I am facing an issue with multiple Bootstrap 4 switches that are dynamically loaded onto the page using JS append. I need to call a function when the switch changes. The example below works fine when the switches are added in HTML, but it doesn't work ...

The JS Fiddle code fails to function properly once it has been downloaded to the local computer

I came across a helpful example fiddle webpage: jsfiddle.net/yijiang/6FLsM/2 After following examples from others, I attempted to download (right click and Save As) using the latest Chrome browser with the following links: jsfiddle.net/yijiang/6FLsM/2/s ...

The form is failing to redirect to another page

retrieveStudents.js $("#submit").click(function(){ $.ajax({ url: "fetchStudents.php?branchCode=1", datatype:"JSON", success: function(obj){ $("table").append("<form method='POST' action='recordAttendance.php'> ...

How can I modify a dynamically generated table to include rowspan and colspan attributes in the rows?

My table was automatically created using data from the database. var rows = ""; rows += "<tr class='row_primary'>"; rows += "<td>COL 1</td>"; rows += "<td>COL 2</td>"; rows += "<td> ...

Should you approach TypeScript modules or classes with a focus on unit testing?

When it comes to unit testing in TypeScript, which content architecture strategy is more effective: Creating modules or classes? Module Example: moduleX.method1(); // Exported method Class Example: var x = moduleX.method1(); // Public method ...

Why does jQuery treat an integer as a string when adding it to a variable?

While working on a for statement, I encountered an issue with adding an integer to a variable that increments. Strangely enough, the addition operation treats the integer as a string. However, other operations like subtraction or multiplication behave as e ...

What is the best way to include additional fields within an array of objects in a mongoose schema, where these objects reference another mongoose schema?

I have a user mongoose schema with the field 'viewed_posts', which is an array of objects referencing another mongoose schema (post). Now, I need to add two more fields inside these objects. This was my attempt: viewed_posts: [ { hits: ...

CSS Challenge: How to crop an image without using its parent container directly

I'm currently facing a complex CSS challenge that I can't seem to solve. I want to create an image controller (two-by-two layout on two lines) that can display: The top-left image in full size, The top-right with horizontal scrolling, The botto ...

Set the minimum height of a section in jQuery to be equal to the height of

My goal is to dynamically set the minimum height of each section to match the height of the window. Here is my current implementation... HTML <section id="hero"> </section> <section id="services"> </section> <section id="wo ...

Text color wave effect - mimic a block of colors flowing through text

I'm experimenting with creating a unique text effect where, upon hovering over the text, it appears as though a block of color is passing through it. Inspired by the technique showcased in this first example (specifically for the word "Kukuri"), I ut ...

In PHP, you can use the `echo` statement to output an HTML input

Incorporating HTML into PHP using heredoc methodology can sometimes lead to challenges when trying to retrieve user input variables. Attempting to access the input variable with $_GET["input"] may result in an error message indicating an undefined index: ...

How can I manage the asynchronicity of Hapi.js, fs.readFile, fs.writeFile, and childProcess.exec?

My code execution seems to be resulting in an empty list, could it be that my asynchronous calls are incorrect? I've tried rearranging and breaking things into functions but there still seems to be a timing issue with my execution. The order in which ...

Where should a controller.js file be located within an Express.js application directory?

When it comes to structuring controllers in an Express.js project, there are a few options to consider. One approach is to have a separate folder within the root directory dedicated specifically to controllers. Another option is to have each route's c ...

A problem occurred while compiling the 'SharedModule' template: The expression form is not compatible with the current system

In creating this share module, I have included the following components: @NgModule({ declarations: [ , DateToPersian , EnumToArrayPipe , SearchWtihInput , ConvertbytePipe , ArraySortPipe , MonySplitePipe , IsEllipsisActiveDir ...