After successfully creating a new user using mongoose at a certain route, I noticed that the validation appears in the console and the user is stored in the mongo database. However, when attempting to create a second user with a different username, an error occurred:
(node:16480) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: .users index: userName_1 dup key: { userName: null }
- Why does the index userName_1 exist?
- What is the origin of the key userName?
- Why is it showing the value as null?
- Is there a way to resolve this issue?
router.post('/register', (req, res) => {
User.findOne({username: req.body.username}, async (err, user) => {
if (err) throw err
if (user) res.json('User already exists')
if (!user) {
const hashPassword = await bcrtypt.hash(req.body.password, 10)
const newUser = new User({
username: req.body.username,
password: hashPassword,
})
await newUser.save()
res.json('User created!')
console.log(newUser)
}
})
})
This represents the Schema structure:
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
lowercase: true,
},
password: {
type: String,
required: true,
}
}, {
timestamps: true,
})