Sparse: MongoError: E11000 duplicate key errorjavascript

Question:

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

add-manager.js

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);
    })
}

news.js

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

error:

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.

db.contacts.getIndexes()
[
    {
        "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
    }
]

Answer

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')
    原文作者:Steven
    原文地址: https://segmentfault.com/a/1190000016068558
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞