欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mongoose经常返回e11000 error的原因分析

程序员文章站 2022-04-29 16:34:01
发现问题 最近在工作中遇到了一个问题,在定义了schema之后,每一次save都会报e11000,但是db.xxx.find()里面根本就没有冲突的条目,什么情况呢?...

发现问题

最近在工作中遇到了一个问题,在定义了schema之后,每一次save都会报e11000,但是db.xxx.find()里面根本就没有冲突的条目,什么情况呢?

问题分析

可能问题出在定义的schema的成员使用了unique,比如:

var catalogschema = new schema({
 idcat: {
 type: string,
 default: '',
 trim: true,
 unique: 'id should be unique!',
 required: 'id cannot be blank'
 },
 titlecat: {
 type: string,
 default: '',
 trim: true,
 unique: 'title should be unique!',
 required: 'title cannot be blank'
 }
 });

mongoose.model('catalog', catalogschema);

unique表示,不能冲突,迷惑的地方就是,没有冲突啊,其实还有一种可能,或许你压根想不到,就是确实冲突了,因为你给成员改名了。

用mongodb的命令行工具查看就知道:

> db.catalogs.getindexes()
[
 {
 "v" : 1,
 "key" : {
  "_id" : 1
 },
 "name" : "_id_",
 "ns" : "ocr-dev.catalogs"
 },
 {
 "v" : 1,
 "unique" : true,
 "key" : {
  "name" : 1
 },
 "name" : "name_1",
 "ns" : "ocr-dev.catalogs",
 "background" : true
 },
 {
 "v" : 1,
 "unique" : true,
 "key" : {
  "title" : 1
 },
 "name" : "title_1",
 "ns" : "ocr-dev.catalogs",
 "background" : true
 },
 {
 "v" : 1,
 "unique" : true,
 "key" : {
  "idcat" : 1
 },
 "name" : "idcat_1",
 "ns" : "ocr-dev.catalogs",
 "background" : true
 },
 {
 "v" : 1,
 "unique" : true,
 "key" : {
  "titlecat" : 1
 },
 "name" : "titlecat_1",
 "ns" : "ocr-dev.catalogs",
 "background" : true
 }
]

问题解决

里面的name和title就是之前的名字,改成了idcat和titlecat,但是成员还是会在mongodb里面,所以,你要做的就是删除这个collection然后在重新运行mongoose了:

> db.catalogs.drop()
false
> db.catalogs.getindexes()
[ ]

然后再在代码里面插入就不会有问题了。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。