Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 }

  1. Where did the index userName_1 came from?
  2. Where did the key userName came from?
  3. Why is this the value null?
  4. 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,
})
question from:https://stackoverflow.com/questions/65940505/mongo-is-creating-index-with-key-value-null-automatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
124 views
Welcome To Ask or Share your Answers For Others

1 Answer

From your schema:

username: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
}
    

Mongoose will automatically create an index to enforce unique. This is correct, as it does not have to do a lookup before the insert to enforce it, so it is faster.

Double check that the username field is actually getting saved as you would expect in the database. The required: true should be picking that up, but the error message is showing that you somehow have a null username.

Also - because you are using lowercase your findOne might not be suitable to determine if the User already exists. I.e. If I create a user "adam", then try to create a user "Adam", that will cause an error, because the lookup for "Adam" will find nothing, but the schema will then lowercase the value to save it "adam", and the index will fail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...