Using sparse: true still getting MongoError: E11000 duplicate key error


Schema (../models/add.js)

var addSchema = new Schema({
    name: {type: String, unique: true, sparse: true},
    phone: Number,
    email: String,
    country: Number

module.exports = mongoose.model('Contact', addSchema);


var Add = require('../models/add.js');
var AM = {};
var mongoose = require('mongoose');
module.exports = AM;

AM.notOwned = function(country, callback)
    Add.update({country: country}, {country: country}, {upsert: true}, function(err, res){
        if (err) callback (err);
        else callback(null, res);


// if country # is not in the database
    AM.notOwned(country, function(error, resp){
        if (error) console.log("error: "+error);
            // do stuff


MongoError: E11000 duplicate key error index: bot.contacts.$name_1  dup key: { : null }

After seeing the error message, I googled around and learned that when the document is created, since name isn't set, its treated as null. See Mongoose Google Group Thread The first time AM.notOwned is called it will work as there isn't any documents in the collection without a name key. AM.notOwned will then insert a document with an ID field, and a country field.

Subsequent AM.notOwned calls fails because there is already a document with no name field, so its treated as name: null, and the second AM.notOwned is called fails as the field "name" is not set and is treated as null as well; thus it is not unique.

So, following the advice of the Mongoose thread and reading the mongo docs I looked at using sparse: true. However, its still throwing the same error. Further looking into it, I thought it may be the same issue as: this, but setting schema to name: {type: String, index: {unique: true, sparse: true}} doesn't fix it either.

This S.O. question/answer leads me to believe it could be caused by the index not being correct, but I'm not quite sure how to read the the db.collection.getIndexes() from Mongo console.

        "v" : 1,
        "key" : {
            "_id" : 1
        "ns" : "bot.contacts",
        "name" : "_id_"
        "v" : 1,
        "key" : {
            "name" : 1
        "unique" : true,
        "ns" : "bot.contacts",
        "name" : "name_1",
        "background" : true,
        "safe" : null

What can I do to resolve this error?

Problem courtesy of: thtsigma


You need to drop the old, non-sparse index in the shell so that Mongoose can recreate it with sparse: true the next time your app runs.

> db.contacts.dropIndex('name_1')
Solution courtesy of: JohnnyHK


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.