What might be the reason behind findByIdAndUpdate not updating the document?

I've encountered an issue with the updateLine function below:

export function updateLine(req: Request, res: Response) {
    if (!req.params.id || !req.body) return res.status(400).send({ message: 'Client has not sent params' });
    Line.findByIdAndUpdate(req.params.id, req.body, async (err, lineUpdated) => {
        console.log("req.params.id", req.params.id)
        console.log("lineUpdated", lineUpdated)
        console.log("req.body", req.body)
        if (err) return res.status(409).send({ message: 'Internal error, probably error with params' });
        if (!lineUpdated) return res.status(404).send({ message: 'Document not found' });
        if (req.params.id !== lineUpdated.id) await Key.updateMany({ 'line': req.params.id }, { 'line': lineUpdated._id }).exec(err => {
            if (err) return res.status(500).send({ message: 'Key Internal Server Error' });
        });
        return res.status(200).send({ data: lineUpdated });
    });
}

The objective is to update the document req.params.id with the contents of req.body.

Here are the responses from the console.log() statements:

req.params.id ACCSEH
lineUpdated {
  _id: 'ACCSEH',
  name: 'Accesorios (SEH)',
  started: 2020-04-21T20:25:10.395Z,
  __v: 0
}
req.body { id: 'ACCSEJ', name: 'Accesorios (SEH)' }

Am I missing something in my implementation?

I am aware that the lineUpdated variable may not reflect the changes immediately. So when querying for changes, it might seem like nothing has happened.

enter image description here

Answer №1

When looking at the official documentation:

The field labeled _id is specifically designated as the primary key, requiring a unique value within the collection. This value remains fixed, cannot be altered, and must not be an array.

It is important to note that once the _id field is added to the collection, it remains unchanged.

Answer №2

If you are looking to locate and modify an entry based on its ID, remember not to include the ID itself in the object. Instead, provide an object containing a mix of other attributes like name, started, or _v.

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

Is the process of adding a new row by duplicating an already existing row dynamic?

I've encountered an issue where a row in a table is not being displayed because the CSS style has been set to display:none. Here's the HTML table: <table class="myTable"> <tr class="prototype"> ........ </tr> </ ...

Unsatisfied Dependencies in NPM

Despite searching extensively on SO and across the web, I have yet to find a solution to my issue. I am in the process of creating a package of React Native components for use in various other React Native projects. The goal is for other teams to simply ad ...

Tips for adjusting date formatting to suit different languages

Currently, I am working with the English locale of en-US and the French locale of fr-CA. Is there a way to convert an English date format like 05/31/2018 to a French date format like 31/05/2018? ...

Retrieve form input from a servlet using a name attribute such as "input[]"

Looking to retrieve input values from a form on my JSP page where each input shares the same name. Take a look at this JSFiddle Any suggestions on how I can access these inputs from my servlet? I attempted using String[] description = request.getParamete ...

What are the steps to creating a unique event within an AngularJs service?

In the midst of my AngularJs project, I find myself faced with a dilemma. I have a service designed to manage button events, but I want another service to handle these events indirectly without directly interacting with the buttons themselves. So, my goal ...

Tag system - Quickly find what you're looking for with the click of a button

I am looking to create a search function based on tags. The idea is that when a tag is clicked, all content with the corresponding tag value (like model, tag1, tag2, etc.) will be displayed. I have already created a page and tested it to see if it can show ...

Having trouble with implementing text index search in MongoDB using C#?

I have added a text index to my collection and I am attempting to filter the data using text search along with additional filters. However, the results are not as expected when combined with other filters. {$text:{$search:"test"},Type:"5&quo ...

Validating whether a condition aligns with any element within an array in JavaScript

Is there a better approach to determine if a condition matches any value in an array? For example, if I want to implement retry logic when receiving a 5xx error. var searchUserRequest = httpClient.request(searchUserRequestOptions, (res => { if(r ...

Encountering a 404 error while attempting to retrieve data from Node.js within a React.js application despite the server being operational

This is my first time delving into the world of back-end development, and it's quite challenging for me. The tech stack I'm using includes React.js, Node.js, express.js, and mysql. However, when I try to fetch the result of a query, I keep runnin ...

Verify your identity using Google reCaptcha during Passport authentication

I am currently working on integrating google reCaptcha into my signup form's back-end, which already includes passport authentication. The code I have so far looks like this: app.get('/signup', function(req, res) { // render the ...

Using AngularJS to dynamically update the DOM with the response from a service method

Here's the HTML code: <div ng-controller="AutoDeployController as autoDeploy"> <input type="text" ng-model="autoDeploy.message"> <p>Message: {{ autoDeploy.message }}</p> </div> <button ng-click="autoDeploy.chan ...

Using jQuery for transferring data from one page to another resulted in an undefined index error in PHP MySQL

This is my first project where I implemented Jquery for the first time. The project consists of two pages: 1. listofleaders.php and 2. leadersprofile.php On the first page, listofleaders.php, there is an input text box where users can enter a leader' ...

Passing a function as a prop to a component in Typescript React/Nextjs with styled-components triggers an error due to a missing

I'm currently learning typescript and encountering an issue with passing the function "toggle" as a prop to the styled-component "MobileIcon". I have defined the type for the function "toggle" in the interface IProps and included it in the styled-comp ...

Turn off autocomplete feature for forms using React and Material UI

I've been diving into React and Material UI to enhance my web development skills. While working on a web form, I encountered an issue where Chrome autofills the text fields with previous data and changes the background color to yellow upon page load. ...

Converting jquery-steps to an AngularJS directive

Currently diving into my first angularjs directive project, I decided to incorporate jquery-steps (https://github.com/rstaib/jquery-steps) into a directive. However, I encountered an issue when attempting to bind inputs or expressions within the steps&apos ...

Discovering the absent number within a cyclical array

Looking to find the missing number between two arrays in a cyclical manner using either Javascript or jQuery. It's easy to find all missing numbers, but I specifically need to identify the single missing number within the range of the second array whi ...

Using Arrow Functions in Angular 2 Typescript with Support for IE11

Are arrow functions in Typescript for Angular2 compatible with IE 11? I have come across information stating that arrow functions in javascript may not be supported in IE 11, but I am uncertain if the same applies to Typescript. ...

Having issues with jQuery animation not working correctly?

Here is the code snippet I am working with: function move() { $(document).mousemove(function(e){ var x = e.pageX; $('.linkHover').animate({'right': '=' + x + 'px'}, 'slow'); }); ...

Saving data inputted in a form using ReactJS and JavaScript for exporting later

What is the best way to save or export form input in a ReactJS/JS powered website? For example, if I have a form and want to save or export the data in a format like CSV after the user clicks Submit, what method should I use? Appreciate any advice. Thank ...

Using ion-list with multiple *ngFor loops

I am trying to combine data from two arrays, "subtitles" and "title", into an ion-list so that each ion-item displays a title on top of a subtitle. How can I achieve this? In my .ts file: items = [ 'Email', 'Phone Number', 'Add ...