Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
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
    }
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda