0

I'm trying to add a user to my users collection and keep getting a duplicate null key value error.

My Users model used to look like this like this:

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  profilePictures: [{
    link: {
       type: String
    }
    rank: {
       type: Number,
       unique: true
    }
  }],
});

module.exports = User = mongoose.model("users", UserSchema);

Before I changed the pictures field to

...
pictures = []
...

I believe because I saved users under the former schema, it has saved somewhere the model of the object in the pictures array (they would be given an ObjectId when I saved something to that array). Even though I have changed the field to

pictures = []

I still get this error

E11000 duplicate key error collection: testDB.users index: profilePictures.rank_1 dup key: { profilePictures.rank: null }

When neither profilePictures nor rank fields even exist anymore. I imagine I can probably just delete the users collection and start again but I want to know if there is a better way to handle this error? Suppose I had 100 users in the users collection – I wouldn't be able to just delete them all. Thanks!

1 Answer 1

2

you added unique property true in your model to profilePictures.rank. on first request it is saving null as you may be not providing rank in your query.

second time it is again trying to save null but it is also marked unique so it is throwing exception.

solution:

  • remove unique flag from profilePictures.rank

  • provide unique value for profilePictures.rank

Sign up to request clarification or add additional context in comments.

2 Comments

But how can I remove it? The profilePictures field doesn't even exist anymore. db.users.find() Does not display the field.
Remove it from the index. use mongodb compass. navigate to the collection and go to the indexes section. Or you can just drop the table or database and try again. it is the easiest way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.