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

14

6

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

Byway answered 10/9, 2020 at 11:0 Comment(4)
Please check whether the user document that you are saving has a not null username. I think during the first and second time username is passed as null to the database.Interpolate
Yes, thats what is happening, but how do I change that? Any suggestionsByway
Can you add the code that is actually using the model to save the user? It looks like it is not using the required: true, if it is saving without a usernamePiton
For me , this error came because I wasn't sending a response on successful operation.Ebonyeboracum
S
20

ONLY FOR TEST DTABASE


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

Stites answered 4/5, 2021 at 21:26 Comment(4)
do you know why this error happens? also your solution worked!!Aube
Imagine this happening in a prod env and the solution is to drop the collection wtfNels
same thoughts @JorgeDiaz, this dropping of collection is not the real answer to solutionJegar
open to mongoDB Compass → database from left → open the desired collection → select indexes tab and remove the entry that is causing the issue.Matrices
P
4

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

Protozoon answered 18/2, 2021 at 17:56 Comment(1)
not the idea solution, imagine this is on production levelJegar
D
2

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

Dashtilut answered 19/3, 2021 at 16:21 Comment(0)
I
2

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

Iene answered 3/4, 2021 at 8:54 Comment(0)
S
1

Your collection has a extra index named username_1 which is causing this error. When you already have 1 document in your collection with that parameter (username_1) as null, mongodb does not allow to add one more document after that with the same paramter as null (which you are doing without knowing).

How to fix it? You need to delete the index named username_1 from your collection. If you are using MongoDBCompass, go to Indexes and delete the index named username_1.

Scrivings answered 26/3, 2023 at 19:37 Comment(0)
A
1

dropping the collection from Mongo DB worked for me, but can anyone explain this

Antrim answered 5/9 at 14:3 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Dada
C
0

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 :-)

Caneghem answered 20/9, 2021 at 14:27 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Dada
W
0

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

Worcestershire answered 2/3, 2022 at 22:50 Comment(0)
E
0

Thank you @alps solved my issue here is copy paste for beginners: add username: profile.displayName in my User.findorcreate function for reference:

For Google:

function(accessToken, refreshToken, profile, cb) {
    console.log(profile);
    User.findOrCreate({ username: profile.displayName, googleId: profile.id }, function (err, user) { 
     return cb(err, user) 
    });
}

For Facebook:

function(accessToken, refreshToken, profile, cb) {
    console.log(profile);
    User.findOrCreate({ username: profile.displayName, facebookId: profile.id }, function (err, user) {
      return cb(err, user);
    });
}
Elmaelmajian answered 15/3, 2023 at 17:15 Comment(0)
T
0

Delete all the indexes on database once and try again, I am sure this will work

Tope answered 6/7, 2023 at 17:23 Comment(0)
J
0

It's possible that you set the username to be unique in your model and must have likely created the initial document in your collection.

To solve the problem, navigate to the index in your collection and delete the username.

It should work

db collection index

Jabalpur answered 10/8, 2023 at 20:39 Comment(0)
E
0

If you're using MongoDB. Delete your database using Mongo Compass or using terminal.. Thats works for me.

Extremity answered 22/3 at 13:56 Comment(0)
U
0

It helps to drop the database once which you are using, then restart the server again...

  1. show dbs
  2. use myDatabase // the one which you want to remove, i.e. replace "myDatabase" accordingly
  3. db.dropDatabase()
  4. show dbs() // run your server again then problem will be solved.
Unconventionality answered 22/6 at 10:41 Comment(0)
Q
0

Just Go In mongodb Database Section and Delete the Indexes named user_id user_id1 marked as the unique indexes in db ,

Quinta answered 22/6 at 15:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.