Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda