Search code examples
mongoosenullduplicatesunset

unset field that is indexed makes : E11000 duplicate key error collection


I have table "users" with index "phone" When i try to unset a field that is indexed, first time it's correctly unsetted, and this query return the users that now haven't field "phone"

db.getCollection('users').find({"phone":null})

but when i try to unset annother user's field phone t i receive this error :

MongoError: E11000 duplicate key error collection: fflok.users index: phone_1 dup key: { : null }

please help

this is the query of unset field

User.updateOne({ _id: userId }, {$unset: {phone: 1 }}, callback);

Solution

  • i tried this code in schema :

     phone: {type: String, trim: true, index: true, unique: true, sparse: true},
    

    and on database i selected sparse on the index : enter image description here