Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values.

Here is the code snippet:

router.put('/:id' , (req,res, next) => {
  Student.findById(+req.params.id)
  .then(data => {
    let arr = data.dataValues;
    res.render('edit', {
      files : arr
    })
  })
  .catch(err => {
    res.status(404).send('something went wrong');
  })

  const  theKey = key => key || undefined
    const {first_name, last_name, email } = req.body
    let obj = {
      first_name : theKey(first_name),
      last_name: theKey(last_name),
      email: theKey(email),
      createdAt: new Date(),
      updatedAt: new Date()
    }
    Student.update(obj,
        { returning: true,
          where: {
            id : req.params.id
          }
        })
    .then(updated => {
      res.send(`updated`)
    })
})

Snippet from my app.js:

app.use('/students/edit', editstudent )

However, I am encountering an issue where data does not get updated when navigating back to the student list in the database. Could there be an error in my PUT method implementation?

Answer №1

res.render('edit', {
  data : files
})
.then(updated => {
  res.send(`Success: Student updated`)
})

The issue here is that the rendering of the page happens before the student data is actually updated. It would be better to update the student first and then render the page.

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

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...

Leverage the power of Angular and Node.js to dynamically generate and configure a new subdomain on an

Currently, I am tackling a project that involves generating sub domains dynamically based on the prefixes entered by users on my website. While everything is functioning properly on my localhost using diet.js and express-subdomain, errors are being encount ...

Encountering the "ERR_FILE_NOT_FOUND" message within the popup of my Chrome extension

Currently, my manifest file is structured as follows: { "manifest_version": 2, "name": "My Extension", "description": "A starting point for creating a functional Chrome extension", "version": "0.0.1", "browser_action": { "default_popup": " ...

Mastering the Art of Importing JS Modules in a Nodejs-Express Environment

Currently, I am in the process of learning how to utilize nodejs with express as my framework and handlebar as the template engine. Note: This information is taken from the chartjs tutorial where they employ parcel. However, when attempting to replicate ...

The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users. Interestingly, the error messages seem to appear fine in the developer to ...

Modify the CSS using JavaScript after a brief delay

I'm creating a homepage that includes animations. Inside a div, I initially have display: none, but I want it to change to display: block after a few seconds. I've been trying to use JavaScript for this purpose, but I'm struggling to find th ...

Converting numbers in React Native, leaving only the last four digits untouched

When mapping biomatricData.ninId, the value I am receiving is "43445567665". biomatricData.ninId = 43445567665 My task now is to display only the last 4 digits and replace the rest with "*". I need to format 43445567665 as follows: Like - *******7665 ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Creating objects that are a fraction of another's width

My goal is to create 3 responsive divs that fill the width of the window and adjust their width based on the window dimensions. However, I'm facing an issue with JavaScript where it seems to be miscalculating the window width, causing the objects to o ...

Socket.io: sending signals without receiving any responses

I've been working on a real-time socket.io project that involves a collaborative whiteboard app. I'm facing some issues with emitting data. server.js const express = require('express') const app = express(); const http = require(&apos ...

Capture environmental data from JSON response in a Postman script

I have retrieved the following data: { "dbflash:db-files": { "db-file": [ { "usageStatus": "Backup", "dbFileName": "DB_1710013320170619041443", }, { "usageStatus": "Current", "dbF ...

When the button is clicked, the JavaScript function is not being executed

I'm having a strange issue with my second button not working as expected. Despite appearing to be straightforward, the "Reset" button does not seem to be triggering the clear() function. Within the HTML code, I have two buttons set up to interact wit ...

Please provide the date using the Foundation Datepicker tool

Beginner in JavaScript here! I am having an issue with submitting dates selected using the Foundation Datepicker from . I have searched for solutions on StackOverflow like Post form on select with JQuery Datepick, but none seem to work in my case. If a Ja ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

Adding new information into a database field through an HTML table

Can anyone help me figure out how to insert data from an HTML table into a MySQL database with the click of a button? Here is what my table looks like: <table> <tr> <th>Name</th> <th>Number</th> </tr> ...

Strip away the HTML tags and remove any text formatting

How can I effectively remove HTML tags and replace newlines with spaces within text? The current pattern I am using is not ideal as it adds extra space between words. Any suggestions on how to improve this pattern? replace(/(&nbsp;|<([^>]+)> ...

I am currently encountering a "401 Unauthorized" problem within my Mern application

I've encountered an issue while trying to send a Put request to update user profile information on my backend API. Despite implementing token-based authentication and storing the token in local storage upon login, I keep receiving a "401 Unauthorized" ...

What is the reason behind Meteor automatically updating a record without the need to run a "Meteor.call" function for an update?

I am currently developing a Meteor.js application and while I have grasped the basic concepts of Meteor, I feel like I might be missing something when it comes to its reactivity principles. Using angular-meteor, I am utilizing a $scope variable in my view ...

Display a placeholder page during the processing of an asynchronous task by Express JS

Perhaps this issue is either too simple to be overlooked or too complex to tackle, but despite my efforts of over 3 hours searching for a solution, I am unable to find one. It seems like it should be a common problem and I am just too inexperienced to loca ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...