The Model.updateOne() function seems to be failing to update some fields

I am attempting to execute a PATCH update on a MongoDB document. I fetch the existing document using Mongoose in the following manner:

const ratePlan = await RatePlan.findOne({
  _id: req.params.id,
})

The code snippets provided above work effectively in updating the model with the data from the HTTP request (req.body):

for (const [key, value] of Object.entries(req.body)) {
  ratePlan[key] = value
}
await ratePlan.save()

// - OR -

await RatePlan.replaceOne(
  { _id: ratePlan._id },
  {
    ...ratePlan.toObject(),
    ...req.body,
  },
  {
    overwriteDiscriminatorKey: true,
    runValidators: true,
  },
)

However, the following code snippet fails to update a specific field that consists of an array of objects (it only updates string and numeric fields):

await RatePlan.updateOne({ _id: ratePlan._id }, req.body, {
  overwriteDiscriminatorKey: true,
  runValidators: true,
})

What could be the reason for updating some fields while neglecting others?

Note: The RatePlan model includes two discriminators, namely 'parent' and 'child', with the discriminatorKey set as 'kind'. The field that is not being updated is exclusively found in the 'parent' discriminator. The document undergoing the update also belongs to the 'parent' discriminator.

Answer №1

Have you double-checked that you're passing the correct array? The replaceOne() function will locate a matching element and completely replace it with new data. If there's even a slight difference in what you're sending, the result will be altered.

I encountered a similar issue once. It turned out that I accidentally provided two sets of curly braces {}, causing the entire field to become empty. As a result, all I was left with was an ID and nothing else.

Could you attempt the following code snippet:

await RatePlan.updateOne({ _id: ratePlan._id }, {req.body}, {
    overwriteDiscriminatorKey: true,
    runValidators: true,
})

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 simple passport.js sign-up feature is not successful as it mistakenly believes that the username is already in

Currently, I am working on setting up a basic signup feature for my Node + Express + Sequelize application using passport.js. The database is empty at the moment, and I am utilizing the passport-local strategy to extract the user's email and password ...

React.js error: Uncaught TypeError: Cannot read property 'map' of null

Hey there, I'm currently working on creating a MERN Stack web app following this tutorial: https://youtu.be/aibtHnbeuio. I'm fairly new to the stack and could really use some help fixing this issue... Error Encountered: TypeError: Cannot read p ...

What is the reason behind the failure of the cancel test?

I've created two test cases; one for testing the functionality of the Download button and the other for the Cancel button. However, I am encountering issues with the Cancel test failing consistently. Below is the code snippet where I'm attemptin ...

Monitor when a button in a grapesjs modal is clicked

When using the Grapesjs Editor, I needed a modal with a form inside it. Upon clicking the submit button, I wanted to trigger a Function that would make an ajax call. To achieve this, I attempted to create a custom component by extending it from the defaul ...

What is the process for modifying a Date type value in JavaScript?

I'm looking to create a graph that illustrates the sun's altitude throughout the day, resembling a sine curve. Users should be able to input a location (latitude & longitude) and a date, and the graph will adjust accordingly. I've incorpora ...

The issue with saving GeoData in Spring Data MongoDB is due to the absence of a property type

Encountering an issue while attempting to update an object with geoData in spring data mongo results in the following exception: org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property type found on org.springframework.data.mon ...

Creating a Chrome extension that opens multiple tabs using JavaScript

Currently, I am working on a chrome extension that includes several buttons to open different tabs. However, there seems to be an issue where clicking the Seqta button opens the tab three times and clicking the maths book button opens the tab twice. Below, ...

Repairing MongoDB Connection After Crash - NodeJS

I currently have a server built with nodejs that utilizes a single MongoDB connection in my index.js file as referenced in this resource. The connection is established when the server starts. Using forever, the module automatically restarts the server if ...

The input field in Angular dynamically populates values into multiple instances of the same text

I am facing an issue with my comment inputs where whatever I type in one input is automatically populated in all other inputs. How can I ensure that the text input value only appears in the input box that I am typing into? Below is a snippet of the templa ...

Ways to access the entire parent element, rather than just the individual child element, following the use of e.target

Looking to target the li element itself when clicked, rather than its child elements. The goal is to determine which specific option the user selects from a dropdown menu using event.target in jQuery. If the user chooses an li with a class of 1, set one gl ...

What is the best way to modify the styling of my CSS attributes?

I'm currently working with this CSS code: input:checked + .selectablelabel .check { visibility: hidden; } Now, I want to change the visibility property to "visible" using JavaScript. I attempted the following: $(document).on('click', & ...

What is the best way to determine the property type dynamically in TypeScript based on the value of another property?

I have been working with Polymorphic relationships and currently have the following TypeScript interface defined: interface SubjectA {} interface SubjectB {} interface SubjectC {} enum SubjectType { SubjectA = 'Subject A', SubjectB = 'S ...

Unable to receive a 404 status code for my setup, receiving a 500 status code instead due to an incorrect id

Recently, I started exploring Nodejs and experimenting with different functionalities using node js. I developed an API (using Nodejs, Express, Mongoose) to retrieve user data. While implementing the functionality to search for a user with an invalid ID ( ...

How to simulate keyboard events when a dropdown list is opened in an Angular application

Requirement- A situation arises where upon opening the dropdown menu, pressing the delete key on the keyboard should reset the index to -1. Steps to reproduce the issue: 1. Click on the dropdown and select an option from the menu. 2. Click on the dropdow ...

Tips for assigning a unique identifier to an HTML tag using JavaScript

When appending multiple items in JavaScript like this: data.context = $('<button class="btn btn-primary"/>').text('Upload') .appendTo('#fileTableId') .click(function () { ...

Transforming button properties into a JSON format

I am currently in the process of developing a web application using node.js and mongodb. Within my app, there is a table that dynamically populates data from the database using a loop. I encountered an issue with a delete function that I implemented base ...

Error message: React router issue (Prop type failure: Prop `children` supplied to `Switch` is invalid, expecting a ReactNode.)

Trying to modify a component in order to create a login page, I attempted to modify App.js but encountered an error. warning.js?6327:36 Warning: Failed prop type: Invalid prop children supplied to Switch, expected a ReactNode. This is the code I have ...

finding the ID of the element that triggered a jQuery dialog

I'm utilizing jQuery dialog to trigger popup windows when buttons are clicked. <script> $(document).ready(function(){ $("#dialog-form").dialog({ autoOpen : false, height : 300, ...

Is there a way to programmatically select an HTML tab or filter in puppeteer?

I am currently developing a web scraping application for a website that utilizes tab headers to filter the contents of a table. In order to extract the data from the table, I need to first select a specific filter by clicking on a tab item. However, I&apos ...

What is the best way to integrate jQuery Masonry with ES6 modules?

Attempting to utilize the npm package https://www.npmjs.com/package/masonry-layout Following the installation instructions, I executed: npm install masonry-layout --save Then, in my file, import '../../../node_modules/masonry-layout/dist/masonry.p ...