【问题标题】:MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index [duplicate]MongoError: insertDocument :: 由 :: 11000 E11000 重复键错误索引引起[重复]
【发布时间】:2017-05-25 20:36:02
【问题描述】:

每当我尝试插入新记录时,我都会遇到错误,实际上用户名本身并不是我的模型的一部分,但我不确定为什么会出现此错误,请谁能猜出错误。

我的错误,

MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: project1.students.$username_1  dup key: { : null }

我的收藏,

 var StudentSchema = new Schema({
  title: { type: String, default: '' },
  first_name: { type: String, default: '' },
  last_name: { type: String, default: '' },
  email: { type: String, default: '' },
  display_name: {
    type: String,
    trim: true
  },
  username: {
    type: String,
    validate: [validateUsername, 'Please enter a valid username: 3+ characters long, non restricted word, characters "_-.", no consecutive dots, does not begin or end with dots, letters a-z and numbers 0-9.'],
    lowercase: true,
    trim: true
  },
 });

我的索引,

 [
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "project1.students"
    },
    {
        "v" : 1,
        "unique" : true,
        "key" : {
            "username" : 1
        },
        "name" : "username_1",
        "ns" : "project1.students",
        "background" : true
    }
]

【问题讨论】:

    标签: node.js mongodb mongoose mean-stack


    【解决方案1】:

    我认为您的用户名已编入索引,因此每当您尝试插入具有相同用户名的文档时,都会出现此错误。索引应该是唯一的。如果用户名不是您模型的一部分,请告诉您的模型架构。

    【讨论】:

    • 在我的模型中我没有任何用户名字段
    • 你能告诉我你的收藏到底是什么,你要寄什么吗?
    • 编辑了我的代码。
    • 请检查哪些文件被索引使用 this-> db.getCollection('students').getIndexes();
    • 是的,您的用户名也已编入索引,因此请使用 -> db.students.dropIndex("username_1")
    猜你喜欢
    • 2017-01-03
    • 2017-03-02
    • 2017-08-27
    • 2019-07-11
    • 1970-01-01
    • 2016-10-31
    • 2021-09-19
    • 2021-03-04
    相关资源
    最近更新 更多