The frequency of database updates exceeds expectations - involving vue.js this.$router.push and express operations

Having some trouble updating a MongoDB with this code. It seems to be updating three times instead of just once due to having three dates in the posts.date field. Utilizing Vue, Mongo, and Express for this project, I have the following data structure:


{
  "posts": [
    {
      "date": [
        { "date": "180320", "attend": "present" },
        { "date": "180321", "attend": "absent" },
        { "date": "180322", "attend": "present" }
      ],
      "_id": "5ab7a6396b92178b5a9c5118",
      "netid": "cjp",
      "name": "Colton"
    },
    // More data entries here...
  ]
}

The issue lies within the following code snippet when trying to update a post. The update process is being triggered three times instead of once:


async updatePost (target, direction) {
  let day = this.today;
  for (let student in this.posts) {
    if (this.posts[student].name == target && direction == 'left') {
      // Code logic here...
      await PostsService.updatePost({
        id: this.posts[student]._id,
        netid: this.posts[student].netid,
        name: this.posts[student].name,
        date: this.posts[student].date
      });
    }
    if (this.posts[student].name == target && direction == 'right') {
      // Code logic here...
      await PostsService.updatePost({
        id: this.posts[student]._id,
        netid: this.posts[student].netid,
        name: this.posts[student].name,
        date: this.posts[student].date
      });
    }
  }
  this.$router.push({ name: 'Posts' });
}

This is causing confusion as it should only update once. Any help or insights would be greatly appreciated! Unfortunately, unable to provide a live example at the moment. Thank you!

Answer №1

It seems like the issue might arise from the fact that the for loop doesn't support the use of async/await. This means that the loop will continue iterating without waiting for the asynchronous code to complete.
I suggest exploring alternatives such as using Bluebird's promise.map method for handling async operations.

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

Using Restify to Serve CSS FilesLearn how to use Restify to

Currently, I am developing a node application that requires serving static files like JavaScript and CSS. In my project structure, I have the following layout: -MyProject -backend -index.js -frontEnd -index.html -js ...

What is the process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

Utilizing JavaScript filtering logic in Angular Filter with AngularJS

This inquiry originates from this source Within the realm of Javascript, I have crafted a code to facilitate filtering, specifically showcasing elements from the array colors only if they correspond as values in cars. var colors = ["blue","red","pink","y ...

Generate a unique token through a personalized form

**HTML** <div ref="addCardForm" id="card-element"> <div class="card_digit_text">Credit Card Number <input type="text" id="cardDigit" name="email" placeholder="0000 0000 0000 0000"> </div> ...

Nextjs compilation error - Unable to locate module: Cannot resolve 'module'

Currently, I am immersed in a nextjs project using wagmi hooks. Recently, Nextjs presented me with an error message indicating that it cannot resolve the 'module' (refer to the error message below). This occurred after resolving the initial error ...

Hosting a WCF service in a virtual directory on a shared hosting environment

In the midst of my work on a next js project, I encountered the need to invoke a wcf service. To rectify an error caused by the secure server hosting the site, necessitating the service also be hosted securely, I resorted to creating a virtual directory ...

The MongoDB operator "$in" does not recognize the type array that currently exists in the field

When attempting to execute an aggregate query in mongodb, I encountered an issue with the "$in" operator stating that the field passed is not recognized as an array. Here is the aggregate query being used: [ { '$match': { 'isVis ...

What is the proper way to implement v-model with Vuex in <select> elements?

I included a <select> element in my design: <select v-model="amount" required> <option value="10">10</option> <option value="20">20</option> <option value="25">25</o ...

What could be causing this error to appear: Unable to locate the file './components/forms/LoginForm'

What could be causing the error message to appear when I run the npm run dev command? npm run development ERROR in ./resources/js/app.js 5:0-53 Module not found: Error: Can't resolve './components/forms/LoginForm' in 'D:\wamp64&bs ...

JavaScript encountering a NaN value

I'm encountering an issue where I am receiving a NaN when attempting to summarize columns of a report. Additionally, my query is only retrieving 1 row of data, but the grid is displaying 2 rows. Does anyone have any suggestions on how to resolve this ...

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

How to emphasize a clicked hyperlink in AngularJS

Here's the HTML code I've been working on: <div id="Navigation" class="md-dialog-full"> <div class="products-options"> <a ng-click='addType("Physical")' href="javascript:void(0);"> < ...

Create a small circle in the bottom left corner with a constrained size

I'm trying to create a circle at the top of the screen on mobile, similar to the image below. The circle should take up a percentage of space, with the rest of the content appearing against a blue background as shown in the image. However, I'm h ...

Vue.js: crafting a universal composable is proving challenging

I am faced with the challenge of making a universal composable. In my scenario, I have 3 components - ItemSwiper, ItemCard, and ViewRecipeDetail. ItemSwiper contains card slides and serves as the parent of ItemCard. The loop of recipes in ItemSwiper loo ...

What is the method to provide function parameters without executing the function?

I'm searching for a solution to obtain a function that requires a parameter without actually invoking the function. Example of current malfunctioning code: const _validations = { userID: (req) => check('userID').isString().isUUID(&apo ...

An error has been detected by Internet Explorer 8 at line number 373402504

Internet Explorer 8 is throwing an error message that seems to be from a different galaxy ("Expected identifier, string or number") at a line number that makes no sense. Surprisingly, the code functions perfectly on FireFox. Checking the source code, I se ...

Form containing a pair of buttons

I am attempting to design multiple forms with two buttons, each of which will submit the form to a different script. One button will use ajax for submission, while the other will simply submit the form without ajax. <?php foreach($objects as $object) : ...

Angular and Bootstrap 5 combine to create a dynamic multi-item carousel featuring animated slide transitions and embedded YouTube videos

I'm trying to create a multi-item carousel using YouTube videos, and although I have managed to get it working with Bootstrap 5 carousel and cards, the animation when the carousel slides is not as smooth as I would like. The issue seems to be that the ...

Enhancing Your WordPress Menu with Customized Spans

I have a WordPress menu structured like this: <div id="my_custom_class"> <ul class="my_custom_class"> <li class="page_item"><a href="#">page_item</a> <ul class='children'> <li class="page_item chil ...

The moment the code throws an error, the Node local server abruptly halts

Within this code snippet, I am attempting to utilize findOne in order to locate and remove a specific dishId from my Favorites document. The code functions correctly when a valid dishId is provided. However, if an incorrect dishId is entered, the code will ...