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

Viewed 4883

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

6 Answers

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

In Robo3T I had to look up my collections indexes, and manually delete the username index.

Deleting the collection and recreating the collection in mongodb worked for me

add a username to your schema, i had the same problem and i did this

function(accessToken, refreshToken, profile, cb) { console.log(profile); User.findOrCreate({ username: profile.displayName, googleId: profile.id }, function (err, user) { return cb(err, user); }); i simply added a username in my findorcreate function so that it does not show username null

Try this out, I wish it will be helpful.

Creating a new Database in MongoDB server and saving the data in that new location, worked for me :-)

the problem is not in this module you presented here.

We need to see your code from your.js file assuming you are using express and body-parser to make all this work. I think and i made a little trial of your app and i can tell that your REQ POST using POSTMAN is incorrect. WHY ? Because you are sending a POST REQ to

   http://localhost:3000/users/add

   and you are setting PARAMS with username: randomguy
   and that's why you're getting that error from MongoDB 
   {username: null}. 

To fix this issue in POSTMAN you must leave PARAMS EMPTY (REMOVE ALL KEY/VALUE FIELDS) and instead make the POST request including KEY/VALUE in BODY Field:

   username: randomGuy

In my case i'm using body-parser like this:

   app.use(bodyParser.urlencoded({ extended: true }));

and in POSTMAN in BODY select the radiobutton x-www-form-urlencoded

/PARAMS is used for GET req/

POSTMAN POST REQ TO local MongoDB with BODY KEY/VALUE

Related