Search code examples
node.jsmongoosebackend

MongoError: E11000 duplicate key error collection: tracker-db.users index: username_1 dup key: { username: null }"


A bunch of similar questions answered before but none of them seem to fix my problem. No problem in adding the first user. However, the username doesn't display the records and gives error on adding the second user.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema(
    {
        username: {
            type: String,
            unique: true,
            required: true,
            minlength: 3,
        },
        gender: String,
        age: Number
    },
    {
        timestamps: true
    }
);

const User = mongoose.model('user', userSchema);
module.exports = User;

The error that I'm getting

The record on adding first user


Solution


  • ONLY FOR TEST DTABASE


    Simply drop the collection and make the request again . This should work just fine.