2016-09-26 23 views
0

我試圖第二次插入文檔時沒有暱稱時出現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

回答

1

所以我擡頭「的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:一個既稀疏又獨特的索引可防止收集文檔具有重複值的字段,但允許多個文檔省略鑰匙。 而這聽起來正是你想要的,對吧? –

相關問題