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

247
Vistas
Cannot register a new user

I am creating a e-commerce website with MERN stack but i cannot register a new user. It only registers the first user when I clear the database but after that it shows an error code. Here is the code: The user Schema:

const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
    {
        username: {type: String, required: true, unique: true,},
        email: {type: String, required: true, unique: true, sparse: true,},
        password: {type: String, required: true,},
        isAdmin: {type: Boolean, default: false,},
    },
    { timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);

The user controller :

const cryptoJS = require("crypto-js");
const User = require("../models/User");
// register
const registerUser = async (req, res) => {
    const newUser = new User({
        username: req.body.username,
        email: req.body.email,
        password: cryptoJS.AES.encrypt(
            req.body.password,
            process.env.SECRET_KEY
        ).toString(),
    });
    console.log(newUser);
    try {
        await newUser.save();
        res.json(newUser);
    } catch (err) {
        res.status(500).json(err);
    }
};

The error :

{
    "index": 0,
    "code": 11000,
    "keyPattern": {
        "name": 1
    },
    "keyValue": {
        "name": null
    }
}
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Error code 11000 (ref) indicates a duplicate value for a unique key. From the error we can read that it is a name field with value null. This means that you are trying to save another document with a null value in the name field, you have a bug in your code which is reading the username incorrectly from the incoming http request (unless you are specifically sending an empty field from frontend). Check the database first to see if you have a document with username null. Then check that you are sending the correct data to the API

over 4 years ago · Santiago Trujillo Denunciar

0

so i think you might previously have had "name" as a required field in your UserSchema definition. therefore it is still expecting every user to have a "name" field and value which explains the error. clearing/syncing indexes should sort it. you can manually dro indexes in mongodb for that specific collection or use mongoose to sync the indexes as seen here.

just seen that OP solved the issue by deleting the database... while this for sure fixes it, it's drastic. i'm certain the error was caused by a missing required field. so if the situation comes up again, just removing indexes will be all the help you need, avoiding dropping other collections that aren't affected by the index.

over 4 years ago · Santiago Trujillo Denunciar

0

Deleting the database from ATLAS helped. I ran the server after deleting the collection from ATLAS and it works fine.

over 4 years ago · Santiago Trujillo 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