Shashith Darshana
Shashith Darshana

Reputation: 2795

How to add a new field to mongodb collection and make it unique?

I have a mongodb collections with several existing data, and now I want to add new field to the same collection at the same time the new field needs to be a unique field.

I'm using nodejs with mongoose.

Following is my current schema.

const user = new mongoose.Schema({
    username: { type: string, required: true},
    token: { type: String, required: true }
});

And now below is my new schema

const user = new mongoose.Schema({
    username: { type: string, required: true},
    token: { type: String, required: true },
    nickname: { type: String, required: true }
});

user.index({ "nickname": 1}, { "unique": true });

Since it has existing data when I run the code it gives me below error.

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

I believe when new field is creating it will be filed with null values. Since the new field is unique it is not allowing multiple null values.

I have scene this document but I can't understand what steps to follow. Please enlighten me about the gap I need to fill.

Thanks in advance

Upvotes: 0

Views: 163

Answers (1)

Nux
Nux

Reputation: 7078

use sparse: true So Make it as

    const user = new mongoose.Schema({
    username: { type: string, required: true},
    token: { type: String, required: true },
    nickname: { type: String, required: true,sparse: true }
});

Hope it helps!

Upvotes: 1

Related Questions