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')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值