Trouble with Mongoose save() function failing to update data

I am currently working on enhancing a fully functioning CRUD app by adding a new feature that allows users to update a list of vendors. They have the ability to add new vendors, update existing ones, and delete vendors. While the add and delete functions are working perfectly, I am encountering an issue with the update functionality. Despite using a similar method that I have successfully implemented elsewhere in the app for CRUD operations, the update is not functioning as expected. Here is the snippet of the code causing the issue:

// async function from AXIOS request
const { original, updatedVendor } = req.body;
let list = await Vendor.findOne({ id: 1 });

if (!list) return res.status(500).json({ msg: 'Vendors not found' });

let indexOfUpdate = list.vendors.findIndex(
  (element) => element.id === original.id
);

list.vendors[indexOfUpdate].id = updatedVendor.id;
list.vendors[indexOfUpdate].name = updatedVendor.name;

const updated = await list.save();
res.json(updated);

Despite console logging that the list.vendors array is being updated, the save() method is not reflecting the changes in the existing document on the database side.

EDIT: I have also tried using an alternative format for the save() method, like this:

list.save().then(res.json(list));

EDIT 2: In response to inquiries about viewing logs, I am unable to share the complete console.log(list.vendors) as it contains sensitive information. However, I can confirm that the modifications made to the list are visible when I execute the following in the VendorSchema:

VendorSchema.post('save', function () {
  console.log(util.inspect(this, { maxArrayLength: null }));
});

Despite this, the changes are still not being reflected on the database side after saving.

Answer №1

When working with nested objects in Mongoose, changes may not be detected automatically. In order for Mongoose to recognize the modifications, you must explicitly mark the modified object before saving it.

list.markModified('vendors');

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

Discovering the oldest date in an array with JavaScript

Is there a way to identify the earliest date, also known as the minimum date, within an array using JavaScript? For instance: ["10-Jan-2013", "12-Dec-2013", "1-Sep-2013", "15-Sep-2013"] The desired output would be: ...

"Implementing drag and drop functionality in Vue.js without the need for a

Exploring html 5 drag and drop functionality using vue js has been a challenging experience for me. After following the w3schools tutorial on drag and drop, I managed to get it working in a basic html file but faced difficulties when implementing it in my ...

Add a new key-value pair to each object in an array, with the value generated by making a request using axios.get

Recently, I've been working on a scraper that has been functioning well until I encountered an issue while trying to scrape data for individual links. Let me clarify the situation: The scraper gathers data about apartments from a webpage where articl ...

Easy steps to prevent window.onbeforeunload from triggering when submitting a form using Vue

Presently, I am utilizing a component named countdowntimer.vue, specifically designed as a countdown timer for an online examination platform. My goal is to implement an onbeforeunload event on the window object while ensuring that the timer automatically ...

Retrieving data from a dynamic form using jQuery

Can someone assist me with the following issue: I have a dynamic module (generated by a PHP application) that includes input fields like this: <input type="text" class="attr" name="Input_0"/> <input type="text" class="attr" name="Input_1"/> ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

"Repetitive" elements arranged horizontally

My goal is to create a looped row of elements, similar to this design: https://i.sstatic.net/7cC2z.png This row should function like a carousel where clicking the "Next" button changes the current element and positions it in the center of the row. I envi ...

Is it possible to link fields with varying titles in NestJS?

Currently, I am developing a NestJS application that interacts with SAP (among other external applications). Unfortunately, SAP has very specific field name requirements. In some instances, I need to send over 70 fields with names that adhere to SAP's ...

Is there a feature in impress.js that allows for navigating to the following slide easily?

Impress.js is an innovative web presentation tool created with Javascript. I am interested in setting up custom events to navigate through the slides. This could involve adding buttons for "Next" and "Previous", for example. The impress.js file itself fun ...

Tips for launching and troubleshooting an AngularJS application within Eclipse

Looking to dive into Nodeclipse and get up and running with debugging an AngularJS application like the angular-phonecat example from Eclipse. Specifically, I want to utilize a Debug on Server launcher to kick off a server with my app and launch a web b ...

Using the ControllerAs syntax in conjunction with $scope methods

Currently working on incorporating the controllerAs syntax into AngularJS 1.3 Here is how I'm starting my function declarations: function() { var myCtrl = this; myCtrl.foo = foo; // Successfully implemented myCtrl.$on("foo", bar); // Enc ...

Unlock the power of json data traversal to derive cumulative outcomes

Our goal is to populate a table by parsing a JSON object with predefined header items. (excerpt from an answer to a previous query) var stories = {}; for (var i=0; i<QueryResults.Results.length; i++) { var result = QueryResults.Results[i], ...

Can we switch the country name to the database name in Jvector?

I've successfully implemented the Jvectormap application and it's functioning as expected. When I click on a country, it displays the name of that country. I have established a simple database for specific countries. Through AJAX, I've conn ...

VueX threw an error stating that it cannot read property 'getters' because it is undefined in Nuxt.js

Just starting out with Vuejs and Nuxt.js. I recently set up a Nuxt project but encountered an error when trying to run it: https://i.sstatic.net/ROtOs.png Any assistance would be greatly appreciated. Thank you. ...

Discover the process of connecting a REST controller with AngularJS and Spring

I have a list of file paths stored in an array within the scope variable of an AngularJS Controller. My goal is to properly map these file paths to a Java REST controller for further processing. When I pass it as "/ABC/Scope-Variable," it successfully ma ...

Troubleshooting Knockout.JS: Why self.myObservable is not working and the importance of code organization

My webpage uses knockout to handle a search field, dropdown selection, and page number. These elements are all initialized with default values for the first run or when the page is accessed. I'm encountering an error that says: "self.selectedTeamId i ...

Is there a way to keep track of changes in multiple dropdowns without having to create a separate JavaScript function for each one

I'm looking for a way to dynamically add more dropdowns as my website grows without having to keep adding new functions to the JavaScript code. Is there a solution for this? Currently, I can add additional functions to the JavaScript like this: ...

Transferring information between components and pages within Next.js involves the passing of data

I currently have an index page set up like this: getServerSideProps(){ //Making two API calls here api1() api2() return{ props:{data:gotDataApi1, data2:gotDataApi2} } } The data retrieved from these APIs is then passed to a component within the index pag ...

What could be causing this JavaScript if statement to malfunction?

I found myself with some free time and decided to create a basic API using JavaScript. What I thought would be simple turned into a frustrating mistake. Oddly enough, my if/else statement isn't working correctly - it only executes the code within the ...

How to insert space after every item generated by ng-repeat in AngularJS

I'm looking to evenly distribute elements based on this inquiry How to distribute li elements equally? I am utilizing angular with jade: ul li(ng-repeat="item in items") {{item.name}} However, ng-repeat does not create newlines after each element ...