Code -11000 --"keyPattern": { "email": 1}, "keyValue": { "email": null }

I have 3 collections in my database-- Users, Posts, type.
User model–const userSchema = new Schema( {
username:{
type:String,
required:true,
unique:true,
},
email:{
type:String,
required:true

},
password:{
type:String,
required:true,
},
profilePic:{
type:String,
default:“”,
}

},
{timestamps:true}
);

const User = mongoose.model(‘User’, userSchema);

Post Model–
const postSchema = new Schema( {

title:{

type:String,

required:true,

unique:true,

},

description:{

type:String,

required:true,

},

photo:{

type:String,

required:false,

},

username:{

  type:String,

  required:true,

},

categories:{

  type:Array,

  required:false

},

},

{timestamps:true});

const Post = mongoose.model(‘Post’, postSchema);

Create Post worked once from postman. Now it gives me the following error.

Postman request–
{
“username”:“Mouse”,
“title”:“Cruise along”,
“description”:“The Island”
}

Response----

“index”: 0,

"code": 11000,

"keyPattern": {

    "email": 1

},

"keyValue": {

    "email": null

}

}

I am not sure what I am doing wrong!?

1 Like

Hi @Pranoti_Savadi ,

The 11000 code is a duplicate key error. This means that one of the uniquely defined keys were duplicated by a document insert attempt.

Perhaps the title you are trying to create already exists in the database.

Maybe also the email is defined required but you maybe insert a null… not very familiar with mongoose error types.

Thanks
Pavel

1 Like

The error message is saying that there is already a record with null as the email. If a document does not have a value for the indexed field in a unique index, the index will save a null value for this document. Because of the unique feature, MongoDB will only permit one document that lacks the indexed field. So just remove that null document and it will work.

Or Simply… Just remove the collection (“users”) and insert the data it will work.

1 Like

Since you recommend

or

for an issue about multiple null value with a unique index, perhaps you are not aware about partial indexes.

1 Like

My problem is a bit more complicated, I use idNumber as unique but sometimes I need to use null value, in these cases it shouldn’t check for uniqueness and unfortunately sparse:true doesn’t solve my problem.