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

172
Vistas
Node crashes when a duplicate data is inserted into mongodb

So I was trying to test my node server if it can handle insertion of duplicate data to mongodb and apparently it can't.

Here's the code:

    app.post('/register', async (req, res) => {
    const { email, password, firstName, lastName} = req.body
    console.log(lastName)
    console.log(typeof(lastName))
    pword = await bcrypt.hash(password, 10)
    try {
        const response = user.create({
            email: email,
            password: pword,
            firstName: firstName,
            lastName: lastName
        })

        console.log("User created successfully: " + response)
    } catch (error) {
        return res.json({ status: 'error'})
    }
})

and here's the error:

MongoServerError: E11000 duplicate key error collection: ApartmentDB.UserData index: email_1 dup key: { email: "asdasa" }
    at C:\Users\Hans\Desktop\MobDev Final Project\node_modules\mongodb\lib\operations\insert.js:51:33
    at C:\Users\Hans\Desktop\MobDev Final Project\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
    at handleOperationResult (C:\Users\Hans\Desktop\MobDev Final Project\node_modules\mongodb\lib\sdam\server.js:370:9)
    at MessageStream.messageHandler (C:\Users\Hans\Desktop\MobDev Final Project\node_modules\mongodb\lib\cmap\connection.js:479:9)
    at MessageStream.emit (node:events:390:28)
    at processIncomingData (C:\Users\Hans\Desktop\MobDev Final Project\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
    at MessageStream._write (C:\Users\Hans\Desktop\MobDev Final Project\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at MessageStream.Writable.write (node:internal/streams/writable:334:10) {
  index: 0,
  code: 11000,
  keyPattern: { email: 1 },
  keyValue: { email: 'asdasa' }
}
[nodemon] app crashed - waiting for file changes before starting...

I saw a similar post to mine saying that he was sending two responses, but I don't see that in my case

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The solution is only to add a check in your handler, like so:

app.post("/register", async (req, res) => {
  const { email, password, firstName, lastName } = req.body;
  console.log(lastName);
  console.log(typeof lastName);
  pword = await bcrypt.hash(password, 10);

  const existingUser = user.findOne({ email });

  if (existingUser) return res.send("User already exists");

  try {
    const response = await user.create({
      email: email,
      password: pword,
      firstName: firstName,
      lastName: lastName,
    });

    console.log("User created successfully: " + response);
  } catch (error) {
    return res.json({ status: "error" });
  }
});

Also note that once you add the user you are only console.log()ing the data and not sending any response which will only end up throwing a timeout on your client side.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think you have not used await user.create.

before completing the DB insert operation you are returning response and later DB is throwing an error.

app.post("/register", async (req, res) => {
  const { email, password, firstName, lastName } = req.body;
  console.log(lastName);
  console.log(typeof lastName);
  pword = await bcrypt.hash(password, 10);
  try {
    const response = await user.create({
      email: email,
      password: pword,
      firstName: firstName,
      lastName: lastName,
    });

    console.log("User created successfully: " + response);
  } catch (error) {
    if (error.status === "E11000") { // it could be .status, .code etc.. not sure
      return res.json({ status: "error", msg: "User already exist." });
    }
    return res.json({ status: "error" });
  }
});
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