Mamta
Mamta

Reputation: 35

Create unique array in MongoDB

I have a field of zipcode in which we can enter multiple zipcodes. It is an array field and I want it should be unique.

Mongoose schema -

const RegionalZones = new Schema({
    name :      { type : String, required : true },
    country :   { type : String, required : true },
    zipCodes :  { type : Array,  required : true},
    isBlocked:  { type: Boolean, default : false },
    serviceTax: { type: Number,  default:10},
    cancelFee:  {type: Number,   default: 7.50},
    contractorCancelFee: {type: Number,   default: 7.50},
    createdAt : {type : Date,    default : Date.now},
    updatedAt : {type : Date,    default : Date.now}
});

RegionalZones.index({ country: 1, zipCodes: 1,name:1 }, { unique: true });

module.exports = mongoose.model('RegionalZones', RegionalZones);

Upvotes: 2

Views: 5817

Answers (1)

Israel Zinc
Israel Zinc

Reputation: 2769

the keyword unique means that there will be only one document with this value in the whole collection. For example, if a document has a zip-code 1, no other document will be able to have it, which I assume is not your desired effect.

What you're looking for is the $addToSet command.

My suggestion is that you remove the unique modifier from this field and instead, when inserting data to this array, use the $addToSet command.

Here is a sample code that I used in past projects:

User.findByIdAndUpdate(id, { $addToSet : {accounts : accountId } } )

In my example, it will find an user by id and add one account on it. But if it already have an account, it won't duplicate the value.

Hope it was helpful.

Upvotes: 8

Related Questions