nickheck
nickheck

Reputation: 79

Duplicate key error collection with unique field

I am getting a MongoDB error when trying to insert a document without nickname second time. The document already have unique field and non required.

Here is my Mongoose model:

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
        }

});

For the first time, the document without a nickname is added to the database, but when I want to save another document without a nickname, I get an error:

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

Upvotes: 0

Views: 999

Answers (1)

Nadia Cerezo
Nadia Cerezo

Reputation: 602

So I looked up "MongoDB not required but unique" and I found this: mongoDB/mongoose: unique if not null

It seems you need to use sparse: true instead of required: false to get what you want.

Edit: Reading up the MongoDB documentation on sparse indexes, however, I was redirected to partial indexes which seem to be the way to go from MongoDB 3.2 onward: https://docs.mongodb.com/manual/core/index-partial/#index-type-partial

The problem is that while the documentation clearly states:

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

It does not seem to be true for sparse and unique indexes, since they also state on the same page:

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.

Way to contradict themselves... :/

Upvotes: 1

Related Questions