Home > Net >  getting 400 bad request while posting data but data getting saved in database
getting 400 bad request while posting data but data getting saved in database

Time:07-12

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});"

CodePudding user response:

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

  • Related