Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 使用sparse:true仍然得到MongoError:E11000重复键错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
架构(../models/add.js)

var addscheR_604_11845@a = new scheR_604_11845@a({
    name: {type: String,unique: true,sparse: truE},phone: number,email: String,country: number
});

module.exports = mongoose.model('Contact',addscheR_604_11845@a);

附加manager.js

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

Am.not@R_673_11125@d = 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.not@R_673_11125@d(country,function(error,resp){
        if (error) console.log("error: "+error);
        else 
        {
            // do stuff
        }
    })

错误

@H_825_7@mongoError: E11000 duplicate key error index: bot.contacts.$name_1 dup key: { : null }

看到错误消息后,我四处搜索并了解到,在创建文档时,由于未设置name,因此将其视为null. See Mongoose Google Group Thread第一次调用Am.not@R_673_11125@d时,它将起作用,因为没有名称键的集合中没有任何文档.然后,Am.not@R_673_11125@d将插入带有ID字段和国家/地区字段的文档.

后续的Am.not@R_673_11125@d调用失败,因为已经存在没有名称字段的文档,因此将其视为name:null,并且调用第二个Am.not@R_673_11125@d失败,因为未设置字段“name”并将其视为null ;因此它不是唯一的.

所以,按照Mongoose线程的建议并阅读mongo docs,我看了使用稀疏:true.但是,它仍然抛出相同的错误.进一步研究它,我认为它可能是同一个问题:this,但将模式设置为name:{type:String,index:{unique:true,sparse:truE}}也没有解决它.

This s.O.问题/答案让我相信它可能是由索引不正确引起的,但我不太确定如何从Mongo控制台读取db.collection.geTindexes().

db.contacts.geTindexes()
[
    {
        "v" : 1,"key" : {
            "_id" : 1
        },"ns" : "bot.contacts","name" : "_id_"
    },{
        "v" : 1,"key" : {
            "name" : 1
        },"unique" : true,"name" : "name_1","BACkground" : true,"safe" : null
    }
]

我该怎么做才能解决错误

解决方法

您需要在sHell中删除旧的非稀疏索引,以便Mongoose可以使用稀疏重新创建它:下次运行应用程序时为true.

> db.contacts.dropIndex('name_1')

大佬总结

以上是大佬教程为你收集整理的node.js – 使用sparse:true仍然得到MongoError:E11000重复键错误全部内容,希望文章能够帮你解决node.js – 使用sparse:true仍然得到MongoError:E11000重复键错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。