Despite the updates, Express JS PUT request does not successfully save changes

Currently, I have an Express JS application where I am attempting to update an existing user's name using the PUT method. The schema I am working with is a nested array and is structured like this:

https://i.sstatic.net/WDIse.png

The code snippet I am using to update the user's name using PUT is as follows:

router.route('/sensors_update/:_id/')
    .put(function (req, res) {
        console.log("inside update put")
        User.findById(req.params._id, function(err, user) {
            if (err)
                res.send(err);
            console.log(user);
            user.name = req.body.name;
            console.log("User val is" + user);
            user.save();
        });
    });

While I can see the user's name successfully updating in the JavaScript console, I am encountering issues when it comes to saving the user object. I suspect this may be due to the nested schema. Is my assumption correct? Any advice on how to save a user object with nested arrays would be appreciated.

Upon inspecting the console messages:

inside update put
{ _id: 'Manasa',
  name: 'Manasa Sub',
  __v: 0,
  sensors: 
   [ { sensor_name: 'ras',
       _id: 57da0a4bf3884d1fb2234c74,
       measurements: [Object] } ] }
User val is{ _id: 'Manasa',
  name: 'Manas Sub',
  __v: 0,
  sensors: 
   [ { sensor_name: 'ras',
       _id: 57da0a4bf3884d1fb2234c74,
       measurements: [Object] } ] }

I am puzzled as to why the nested array is being accessed when my intention is to only update and save the user's name.

Thank you

UPDATE

_http_outgoing.js:335 throw new Error('Can\'t set headers after they are sent.'); ^ Error: Can't set headers after they are sent.

How can I resolve this issue?

Response :

    {
     "message": "Cast to date failed for value \"7:00\" at path \"time\"",
     "name": "CastError",
      "type": "date",
       "value": "7:00",
      "path": "time"
      }

Answer №1

section, it is evident that the problem does not lie within the nested schema. The error message is explicitly displayed in the console, indicating that a string type value is being passed for a schema that requires a date type. To rectify this issue, it is recommended to adjust the value of time from a string type to a date type. Alternatively, if the intention is to store the time as a string, the schema type for time should be modified from date to string. This can be achieved by specifying time: {type: String}

in the code segment.

Answer №2

One useful technique for updating a nested array in MongoDB is to use the push and set methods. This allows you to update a single field with ease.

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

Utilizing HTML and JavaScript to dynamically switch stylesheets based on the width of

When it comes to using stylesheets for mobile and non-mobile devices, there is a need for different approaches. The idea of comparing browser height and width in JavaScript seems like a good one, but the implementation may not always work as expected. ...

I am struggling to pinpoint the source of the error in my Node.js callback function

Within this function, we retrieve an ID from the Mongo Database and process a function to assign the variable to the GetID variable. "The callback is not functioning correctly" var GetID = function( nameval , callback ){ console.log(nameval); cons ...

Bootstrap modal should be closed by using the back button in bootstrap

Currently, I am in the process of developing an angularjs application that utilizes a bootstrap modal feature. My goal is to have the modal close when the user presses the back button on their phone. I have disabled html5mode, so my URLs include the # sy ...

Utilizing the `this` keyword within a click handler that is passed through an intermediary function

If I initially have a click event handler in jQuery set up like this jQuery('#btn').click(_eventHandler); And handling the event as follows function _eventHandler(e){ jQuery(this).text('Clicked'); } Does the this keyword serve a ...

Error: Attempting to call vector.subSelf method, which does not exist

Currently, I am experimenting with creating a tank game inspired by Isaac Sukin's "Nemesis" game for AngelHack. The specific change I want to make involves using a model of a tank ("Tank.obj") instead of the default cube used as an enemy. However, I ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

What is the best way to eliminate items from an array in a side-scrolling video game?

In my gaming project, I am creating a unique experience where the player needs to collect all the words from a given array. Currently, I am utilizing the shift() method to eliminate elements, as demonstrated in the code snippet below: if ( bX + bird.width ...

What could be the reason for Express indicating that the default view engine has not been defined?

Currently, I am developing an application using Node.js and MongoDB for the backend. Express is being used to test the app, and I am attempting to utilize EJS for rendering my HTML files. However, I am encountering a problem where my default view engine is ...

Changes to a key value are not reflected in the array of objects

When making changes to input fields within an array of records that include Date and Text fields in a table, the data is not updating as expected. I am encountering issues where changing the Date input results in undefined Text values, and vice versa. My g ...

Organize a list of service providers categorized by their type in pug

Looking to categorize a group of users by their specialties. For instance, I aim to gather all Family Medicine providers and showcase their names: Family Medicine: - List item - List item - List item Below is my JavaScript controller for this task: ...

MongoDB failover connectivity

I am currently working on a nodejs application that connects to mongodb for data storage. Using Mongodb's replicaset client connection feature provides added resilience, allowing the application to failover from one server to another in case of failu ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

The arrow icon for selecting input in Material Dashboard React is missing

Source Code View Result Why is the arrow icon not visible when viewing the select like this? I am using "@mui/material": "^5.8.6". Can someone please help me with this? <Box sx={{ width: "auto" }}> <FormControl fullWidth> ...

The Google Drive API's `copyfile` function is limited to accessing all files in the drive, even if just a copy operation is needed

I found a way to copy files using this page https://developers.google.com/drive/v2/reference/files/copy. However, it only works when I request permission , allowing me to modify any file in their drive, which is not ideal. My goal is simply to copy a publ ...

Retrieve an element from an array within a JSON object stored in a MongoDB document

{ "employees" : [ { "name" : "Alice", "id" : "1", "Salary" : [ { "Month" : "January", "Amount" : "5000", }, { "Month" : "February", ...

Refreshing HTML Form upon Submit using JavaScript

I've been searching through various discussions without any luck, but I'm encountering an issue with a form that successfully submits data to a Google Sheet, yet the input fields retain their content after submission. Here is the code: <form ...

When using a variable to fetch data in JSON, an undefined error occurs. However, if a hardcoded index

I am facing an issue while trying to extract and manipulate JSON data from a file for an application I am developing. When looping through the data, I encounter an undefined error that seems to indicate a missing property in the JSON object when accessing ...

I keep encountering an error in the where clause when trying to update MySQL. What could be

I encountered an issue stating Unknown column 'CR0001' in 'where clause' while executing my code. Strangely, the error seems to be related to the id_scooter column rather than CR0001. Below is the snippet of my code: var update = "UPDA ...

Determining the Location of a Drag and Drop Item

I have been utilizing the code found at for implementing Drag & Drop functionality. My inquiry is: How can I retrieve the exact position (x,y) of a group once it has been dragged and dropped? ...

Storing a null value in MongoDB using mongoengine - A step-by-step guide

Currently working with Django and Mongoengine, there's a particular aspect that I find confusing: How can I ensure that {name: null} is stored in MongoDB? While it's straightforward to accomplish this using the Mongo shell, I'm struggling t ...