'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
}
}
Solution 1:[1]
Deleting the database from ATLAS helped. I ran the server after deleting the collection from ATLAS and it works fine.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Raj Aryan |
| Solution 2 |
