When I create a new user (With mongoose) at this route, it is created. I see the validation in the console, and I can also see the user in the mongo database. But when I try to create the second user (With a different username), I get this error:
(node:16480) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: .users index: userName_1 dup key: { userName: null }
- Where did the index userName_1 came from?
- Where did the key userName came from?
- Why is this the value null?
- How do I get rid of it?
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 is the Schema:
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
lowercase: true,
},
password: {
type: String,
required: true,
}
}, {
timestamps: true,
})