THE INN-VISIBLE
THE INN-VISIBLE

Reputation: 155

How to specify field which is array of objects, objects of array has one of attribute as unique but optional in Mongoose?

This is my schema for employee personal information

const mongoose = require('mongoose');
const PersonalInformationSchema = mongoose.Schema({
name: {
        type: String,
        required: true
    },
emails: [{
        email: {
            type: String,
            trim: true,
            unique: true
        },
        isPrimary: {
            type: Boolean
        }
    }]
}, {
    timestamps: true
});
module.exports = mongoose.model('PersonalInformation', PersonalInformationSchema);

In my case I have array emails which is optional for employee but should be unique. When I insert a record without emails, document saves successfully (with empty array emails: []) but in next try it says

"err": {
        "driver": true,
        "name": "MongoError",
        "index": 0,
        "code": 11000,
        "errmsg": "E11000 duplicate key error collection: EmployeePersonalInformation.personalinformations index: emails.email_1 dup key: { : null }"
}

Upvotes: 1

Views: 35

Answers (1)

mickl
mickl

Reputation: 49985

You can add sparse: true to your schema, try:

const PersonalInformationSchema = mongoose.Schema({
    name: {
            type: String,
            required: true
        },
    emails: [{
            email: {
                type: String,
                trim: true,
                unique: true, 
                sparse: true
            },
            isPrimary: {
                type: Boolean
            }
        }]
    }, {
        timestamps: true
});

The sparse property of an index ensures that the index only contain entries for documents that have the indexed field. The index skips documents that do not have the indexed field.

So when empty documents will be skipped you won't get an error from unique constraint.

Upvotes: 2

Related Questions