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
}
}
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
Deleting the database from ATLAS helped. I ran the server after deleting the collection from ATLAS and it works fine.
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.