重复键错误收集与唯一字段

问题描述:

我试图第二次插入文档时没有昵称时出现MongoDB错误。该文件已经有独特的领域和非必需的。重复键错误收集与唯一字段

这里是我的猫鼬模型:

var schema = new Schema ({ 

     username: { 
      type: String, 
      required: false 
     }, 

     nickname: { 
      type: String, 
      required: false, 
      unique: true, 
      trim: true 
     }, 

     status: { 
      type: String, 
      required: false, 
      trim: true, 
      minlength: 1, 
      maxlength: 100 
     }, 

     avatar: String, 

     online: { 
      type: Boolean, 
      default: false 
     }, 

     created: { 
      type: Date, 
      default: Date.now 
     }, 

     device: { 
      type: ObjectId, 
      ref: 'Device', 
      required: false 
     }, 

     createdRooms:[{ 
      type: Schema.Types.ObjectId, 
      ref: 'Room' 
     }], 

     facebook: { 
      facebookToken: { 
       type: String, 
       required: false, 
       trim: true, 
       unique: false 
      }, 

      facebookId: { 
       type: String, 
       required: false, 
       trim: true, 
       unique: false 
      } 
     } 
    }, 

    { 
     toObject: { 
      virtuals: true 
     }, 
     toJSON: { 
      virtuals: true 
     } 

}); 

这是第一次,没有一个昵称文件被添加到数据库中,但是当我想保存另一个文档没有外号,我得到一个错误:

MongoError: E11000 duplicate key error collection: grooptag.users index: nickname_1 dup key: { : null } 
+1

难道不是昵称不是必需的问题,而是独特的吗? –

+1

@NadiaCerezo是的,但如何确保该字段是唯一的,而不是必需的? – nickheck

所以我抬头“的MongoDB不是必需的,但独特的”,我发现这一点:mongoDB/mongoose: unique if not null

看来你需要使用sparse: true而不是required: false来得到你想要的。

编辑:读了稀疏索引MongoDB的文档,但是,我被重定向到这似乎是从MongoDB的3.2以后要走的路部分索引:https://docs.mongodb.com/manual/core/index-partial/#index-type-partial

的问题是,虽然文件中明确规定:

Partial indexes represent a superset of the functionality offered by sparse indexes and should be preferred over sparse indexes.

这似乎并不为稀疏,唯一索引如此,因为他们也同样的页面上注明:

A partial index with a unique constraint does not prevent the insertion of documents that do not meet the unique constraint if the documents do not meet the filter criteria.

与自己相矛盾的方式......:/

+1

谢谢,我会检查并通知你。 – nickheck

+0

这不适合我。似乎“稀疏”仅适用于参考类型字段。 – nickheck

+0

奇怪的是,这里的文档https://docs.mongodb.com/manual/core/index-sparse/ states:一个既稀疏又独特的索引可防止收集文档具有重复值的字段,但允许多个文档省略钥匙。 而这听起来正是你想要的,对吧? –