Encountering a 400 Bad Request error when attempting to post data, but still managing to successfully save

CODE OPERATION: STORING USER DATA IN DATABASE AS A NEW APP USER REGISTRATION.

ISSUE: DATA IS SAVED, BUT RECEIVING "400 BAD REQUEST" AND ERROR MESSAGE IN CONSOLE

ERROR: "Cannot save() the same document multiple times in parallel"

SCRIPT (GENERATING JWT TOKEN AND SAVING IT TO THE DATABASE)

userSchema.methods.generateAuthToken = async function(){
    const user = this;
    const token = jwt.sign({_id:user._id.toString()}, 'helloworld');
    user.tokens = user.tokens.concat({token});
    await user.save();
    return token;
}

SCRIPT (ROUTER FILE)

router.post('/users', async(req,res) => {
    const user = new User(req.body);
    const token = user.generateAuthToken();
    try {
        await user.save();
        res.status(201).send({user, token});
    } catch(err) {
        console.log(err);
        res.status(400).send(err);
    }
})

The error arises when adding the line "const token" and "res.status(201).send({user, token});"

Answer №1

The mistake you made is quite obvious. Make sure to carefully read the error messages:

ERROR : "Can't save() the same doc multiple times in parallel"

The issue stems from the fact that user.generateAuthToken() is an asynchronous task that involves await user.save()

You also need to await it like this:

const token = await user.generateAuthToken();

Consider removing one of the instances of user.save(). Saving the user twice in one request may not be ideal.

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

Tips for initializing store data in vuex before the component is rendered

Currently, I am utilizing Vuex to store a tree structure within the state property. This data is retrieved via an ajax call. The issue arises when the page renders before the variable in the state property has been fully populated. For example: // sth. ...

Unable to invoke the setState function within the onSubmit handler of Formik

Every time I submit my form, I want to display an alert. I attempted to pass my state as a prop to the component, but it didn't work. Here's how my class state looks: this.state = { alert_variant: '', alert_heading: ...

Unable to display response following the submission of a POST request

I'm encountering an issue when attempting to display the response of a post request using node and request. While I can see the response in the console within the service, it does not make its way to the controller. Any insights on why this may be hap ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

Is it possible to utilize setIn for establishing a fresh index on an array that is currently empty?

Having trouble using Immutable in this specific structure: myMap = Map({a: [], b: []}); myMap.setIn(['a', 0], 'v'); An exception is being thrown when trying to do this immutable.js Error: invalid keyPath at invariant (immutable. ...

Using Angular $resource to store an object with arrays

Consider a scenario where we have a User $resource structured as follows: $scope.user = { name: 'John', hobbies: [1, 2, 3] } If we were to save User.save($scope.user) to the server, it would send the following parameters: name: 'John& ...

Methods for dynamically adjusting content based on window width in Three.js

Currently, I have implemented a basic window resizing code in my project: function onWindowResize() { windowHalfX = window.innerWidth / 2; windowHalfY = window.innerHeight / 2; camera.aspect = window.innerWidth / window.innerHeight; came ...

Flipping the switch to illuminate or darken a room

I am working on a project where I want to create a program that turns on a lightbulb when you click on it, and then turns it off when you click on it again. However, I am facing an issue where no matter which light I click on, the first one always turns ...

What could be causing Express to display a different page than the one specified in res.render?

Upon trying to view the compare.ejs page, I encountered an unexpected issue where a different page was being rendered instead. What could be causing this discrepancy? Here is my app.js code: var compare = require('./routes/compare')(nav); app.u ...

Learn how to pass data as props to child components in Vue3

I'm facing an issue where props are initialized, but they disappear after using .mount. Can anyone advise on the correct way to set up props with dynamically loaded components? import {createApp} from 'vue' blockView = createApp(Block); blo ...

Is there a way to create a clickable component for triggering an AJAX call without using a Submit button?

Just starting out with JS/JQuery programming, so please excuse any mistakes or unclear explanations. Any feedback is welcome, even if not requested specifically. I am working with multiple drop down lists that are populated dynamically by data from SQL Ta ...

Rails assets folder is not directed to the specified directory in the layout file

I have a dilemma in the application layout where I'm referencing assets (js, css, and img) in the public/assets/... directory. For example: <link href='assets/images/meta_icons/apple-touch-icon-144x144.png' rel='apple-touch-icon-pre ...

Unusual behavior of the splice function when applied to child nodes

Inside the given ul element, there are four li child elements. If the code below is run in the console: var a = document.getElementsByTagName("ul")[0]; a.childNodes.splice(1, 2, "abc", "cde"); An error will appear with this message: TypeError: a.childNo ...

Process for evaluating information before storing in database: MongoDB

The concept behind the application is to display all "E-number" ingredients found in a product (such as E100 and E200). Let's consider a scenario where we have a variety of products being added to our database (via JSONs, web scraping, or APIs). Each ...

Flot Graphs: A unique dual-axis line chart with the ability to stack data on one axis

Is it possible to utilize the FLOT Javascript library for creating a chart with dual axis and three data sets? I am specifically looking to have one data set on the left axis and two on the right axis. Ideally, I want to stack the two datasets on the right ...

Having trouble making updates to a MongoDB document through Node.js

I am working on the development of an online course platform and facing an issue while adding new video lectures to a specific course. After creating a course, any attempt to add new content triggers an update request, even when adding video lectures that ...

Moving Image Progress Indicator

I am currently developing a progress bar animation that is designed to animate from 0 to a specified percentage when the progress bar becomes visible within the browser's viewport. The animation must always trigger when the element is scrolled into vi ...

What could be causing the failure in Selenium's findElement(By.css("span:contains(string)") method?

I have been attempting to use selenium-webdriver to click on a specific element within a website, which happens to be plain text. However, when I use the following javascript code const spanElement = driver.findElement(By.css("span:contains('TEXT&apo ...

Node.JS program unexpectedly logging MySQL results to console and exhibiting erratic behavior

Recently, I encountered a peculiar error while working with Node.JS MySQL. Strangely, I noticed that a result was being logged in the console without any corresponding code line instructing it to do so. Even more baffling was the fact that when I intention ...

Is there a way to prevent continuous repetition of JavaScript animated text?

I'm working on a code that displays letters and words one by one, but I can't figure out how to stop it from repeating. Can someone help me with this? <div id="changeText"></div> <script type="text/javascript"> var te ...