E11000 duplicate key error collection: archiwiz.clients index: cnic_1 dup key: { cnic: null }

E11000 duplicate key error collection: archiwiz.clients index: cnic_1 dup key: { cnic: null }

为什么会出现此错误?当我的数据库中不再有 Cnic 字段时。

这是我的架构....

      const mongoose = require('mongoose')
      const uuidv1 = require("uuidv1")
      const crypto = require("crypto")
      const { ObjectId } = mongoose.Schema

  const clientSchema = new mongoose.Schema({
   name:{
    type:String,
    trim: true,
    required: true,
    // match:[
    //     new RegExp('^[a-z]+$', 'i'),
    //     'Name Should have alphabets'
    // ]
},

phone:{
    type: String,
    trim: true,
    required: true,
    unique: true

},
email:{
    type: String,
    trim: true,
    required: true,
    unique:true
},
hashed_password:{
    type: String,
    required: true

},
salt:String,
created:{
    type: Date,
    default: Date.now
},
createdBy:{
    type: ObjectId,
    ref: "Admin"
},
updated: Date

})


clientSchema.virtual('password')
.set(function(password){
this._password = password
// generate a timestamp
this.salt = uuidv1()
// encrypt password
this.hashed_password = this.encryptPassword(password)
})
.get(function(){
return this._password
})

clientSchema.methods = {

authenticate: function(plainText){
    return this.encryptPassword(plainText) === this.hashed_password
},

encryptPassword: function(password){
    if(!password) return "";
    try{
         return crypto
                .createHmac("sha1", this.salt)
                .update(password)
                .digest('hex');
    }catch (err){
        return ""
    }
}
  }
module.exports = mongoose.model("Client", clientSchema)

我做了一些更改,在此之前我有一个唯一的 Cnic 字段...我已经删除了 field.When 我创建了第一个用户,它创建成功但是当我创建第二个用户时它在标题中给出了上面的错误...发生了什么以及如何解决它..?

------------------------解决方案---------------- ------------------------

我在我的数据库中放了一个 collection,它对我有用。如果我的@Scott Gnile

,请在评论部分找到详细答案

发生的事情是 MongoDB 不会将模式存储在集合中,就好像它是 SQL 数据库中的 table 一样,但它确实存储了索引。

当您使该字段成为唯一时,MongoDb 在该集合上为该字段创建了一个索引。

因此在插入一个没有该字段的文档后,索引列表中的条目变为 null。当您插入另一个没有该字段的文档时,您试图在集合中插入另一个具有相同值 null 的文档,但它失败了,因为该字段应该是唯一的。

我已经一步步完成了,截图给大家看下:

如果您在该集合中有大量数据,则删除它不是一个选项,因此您可以删除索引,它会正常工作。

  1. 首先,您列出此类集合的索引
  2. 然后,您确定要删除的索引
  3. 您删除索引
  4. 然后您插入之前失败的同一文档

见下文:

但是如果您想要一个跨文档唯一的可选字段,则有一个中间解决方案。这意味着这样的字段不会一直存在,但在存在时必须是唯一的。

解决方案是创建一个稀疏索引。在下图中,您会看到:

  1. 在同一集合上创建了一个新索引(稀疏且唯一)
  2. 索引创建成功,如果唯一字段存在重复值,则不会发生这种情况。
  3. 插入没有唯一字段的文档没有问题
  4. 文档已成功插入,其中包含唯一字段的值
  5. 尝试将另一个文档插入到集合中,其唯一字段的值与前一个文档相同,正如预期的那样,它失败了
  6. 然后,最后,另一个文档被成功插入,该字段具有不同的值。