Tips for implementing a for loop following a mongoDB update?

I am working on a route with the following code :

router.put("/:id", upload.single('doc_upload'), async(req,res)=>{
try{
          const updatedUser = await User.findOneAndUpdate({ "client._id": req.params._id,"clients.documents._id":req.body.doc_id},
          {"$set":{"clients.$[clientFilter].documents.$[documentFilter].status":"uploaded"}},
          {"arrayFilters":[
              {"clientFilter._id":req.params.id},
              {"documentFilter._id":req.body.doc_id}
          ]} ,
          );


for (i=0; i < updatedUser.clients.length; i++) {
            if (updatedUser.clients[i]._id == req.params.id) {
              for (j=0; j < updatedUser.clients[i].documents.length; j++) {
                console.log("this is the status of all my docs" + updatedUser.clients[i].documents[j].status)
                
              }
            }
          }

 res.send(req.file)
 } catch(err){
          res.status(500).json(err);
  }

In this code, the status of the documents is updated from "pending" to "uploaded" after searching for a user. However, the console is still showing "pending" for all documents even after the update. I need help in figuring out how to update the user first and then display the updated status of the documents. Any suggestions?

Answer №1

After confirming that you have seen the database and your required document was updated successfully, it is important to note that Mongoose's findOneAndUpdate function updates the document but does not automatically return the updated document. To retrieve the updated document, you need to include { new: true } as an additional argument, like this:

 let options = { new: true }; DBModel.findOneAndUpdate( findCondition, updateData, options, (error, updatedDoc) => {}); 
By following this approach, your query will now return the updated document and your issue will be resolved.

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

Changing the color of a tooltip for a specific element using Bootstrap 4

Is there a way to customize the tooltip background-color for icons with the classes "alert-danger" to red and "alert-success" to green using the following CSS commands: .alert-danger + .tooltip > .tooltip-inner { background-color: red !important; } ...

Error: script 'start' is not defined on Heroku

Hello there! I'm currently working on deploying an application to Heroku from my GitHub repository. To ensure that everything runs smoothly, I made some modifications to the start script in the package.json file. Specifically, I adjusted it to point t ...

Encountered a 500 internal server error while attempting to establish a connection between React

Encountering a 500 internal server error while trying to connect React with MongoDB using axios. Despite several attempts, the issue persists. Seeking assistance in resolving this matter. ...

Are there any similar tools to Graphstream in Java that can be used with HTML5 using canvas and JavaScript?

GraphStream is a revolutionary graph library created in Java that offers Java developers a simple way to visually represent dynamic graphs either in memory, on screen, or in files. Check out this demo video. With GraphStream, you can effectively handle th ...

Displaying a 404 error page in a Vue.js and Vue Router single-page application when a resource is not

Implementing Vue and Vue Router in a single page application (SPA) has presented me with a challenge. In one of my view components, I query a repository for a specific resource. If the resource cannot be found, I'd like to display a 404 error page wit ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

Binding Entities in C# with MongoDB

Here is the document structure stored in MongoDB: Document 1: { "_id" : ObjectId("5b0d30ae942267c0c8f6229d"), "Expression" : "[tag] = 'Druck1' && [status]='OK'", "Name" : "Druck1 is running", "Actions" : [ ...

When a directive generates an element, the ng-click function may not function as expected

I am developing a custom directive using angularJS. The directive is supposed to replace my custom element with pagination elements. However, the generated elements by the directive contain an ng-click attribute whose value is a function from the controlle ...

Continuing a Sequelize transaction after a loop

I am facing an issue where the transaction in my chain of code is committing immediately after the first loop instead of continuing to the next query. Here is a snippet of my code: return sm.sequelize.transaction(function (t) { return R ...

Utilize dropdown1 to dynamically populate dropdown 2 in AngularJS

Here is the HTML code snippet I am currently working with: <select ng-controller="category" ng-model="selectedTestAccount" ng-options="c.category for c in categories track by c.categoryID" ></select> <select ng-controller="subcategory" ng ...

What is the best way to retrieve the chosen option when clicking or changing using jQuery?

CSS <form name='category_filter' action='/jobseek/search_jobs/' method='get'> <select id="id_category" class="" name="category"> <option value="" selected="selected">All</option> <option v ...

The results generated by the Google Maps API are consistently consistent

const request = require('request'); var geocodeAddress = (location) => { var encodedLocation = encodeURIComponent(location); request({ url: `http://www.mapquestapi.com/geocoding/v1/address?key=APIKey&location=${encodedLocation}` ...

Revamping ng-model in AngularJS

Here is my scenario: cols = [{field="product.productId"},{field="product.productPrice"}]; data = {products:[{product:{productId:1,productPrice:10}, {product:{productId:2, productPrice:15}}]} This is what I want to achieve: <div ng-repeat="product in ...

Using jQuery to remove the td element from an HTML table

Hello everyone, I have a query. I am trying to remove a specific td from a table using JavaScript, but the remove() function is not working. Here is my code: $('.btnEliminarLicencia').off('click'); $('.btnEliminarLicencia&apo ...

There is no throttleTime function available in Angular 6 within Rx Js

Currently, my Angular 6 project is utilizing angular/cli": "~6.1.5 and rxjs": "^6.0.0. As a newcomer to Angular 6, I decided to dive into the official documentation to enhance my understanding. Here's a reference link I found useful: http://reactivex ...

Looking to optimize Laravel performance by eager loading both belongsTo and HasMany relationships?

I have a pair of interconnected models called Product and ProductCategory. Each product belongs to one product category, while each product category can house multiple products. Let's take a look at the models: Product: <?php namespace App\ ...

Angular is encountering an issue where it is unable to read the value of a JavaScript function, despite the object having a value

I have developed some JavaScript functions that involve reading and writing to a JSON file, with the intention of calling them in an Angular environment (from TypeScript code) using the jsonfile library. Below is the code snippet: function savePatient(pa ...

Sorting through items based on several URL parameters

In an effort to be concise yet clear, I am working on an ecommerce website using Next.js and Shopify. This site features products that need to be filterable based on certain attributes. I retrieve products from the Shopify API, each with its own Product Ty ...

A tutorial on creating dynamic text animations: sliding text effects on web pages

Does anyone know how to create a sliding in and out effect like the one on this page: ...

transmitting information to Laravel via ajax

Is it possible to send a multi-step form data separately to the Laravel controller in order to store them into MySQL? An example would be sending the inputs data shown below: <ul> <li> <input type="radio" class="step1r1" value ...