Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
getting 400 bad request while posting data but data getting saved in database

TASK OF CODE : TO SAVE USER DATA INTO DB LIKE WE ARE REGISTERING THE NEW USER IN APP.

PROBLEM : DATA GETTING SAVE BUT GETTING "400 BAD REQUEST" AND ERROR IN CONSOLE

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

CODE (GENERATING JWT TOKEN AND SAVING INTO DATABASE)

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

CODE (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);
    }
    // console.log(req.body);
})

The problem occurs when I am adding "const token" line and " res.status(201).send({user,token});"

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your error is pretty obviouse. You just have to read the error messages:

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

The thing is, that user.generateAuthToken() is an async task that includes await user.save()

You need to await it aswell:

const token = await user.generateAuthToken();

Maybe you remove one of the user.save(). I guess its not the best idea to save the user twice per request

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!