0

I have a schema like this:

const MemberSchema = mongoose.Schema({
  name: {
    type: String,
  },
  email: {
    type: String,
    unique: true
  },
  phone: {
    type: String,
    unique: true
  }
})

and of course email and phone needs to be unique but the thing is either email or phone is optional so they can be empty string.

and when you set them as unique index I get this error

E11000 duplicate key error collection: model.members index: email_1 dup key: { : "" }'

Is there any way to add exception to unique?

Edit

I changed my code like below but still doesn't work.

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

\

'E11000 duplicate key error collection: email-collector.members index: email_1 dup key:{ : null }'

when I run getIndexes, I get

> db.members.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "email-collector.members"
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "email" : 1
                },
                "name" : "email_1",
                "ns" : "email-collector.members",
                "sparse" : true,
                "background" : true
        },
        {
                "v" : 2,
                "unique" : true,
                "key" : {
                        "email" : 1,
                        "phone" : 1
                },
                "name" : "email_1_phone_1",
                "ns" : "email-collector.members",
                "sparse" : true
        }
]
Phillip YS
  • 784
  • 3
  • 10
  • 33

0 Answers0