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