Mohamed Daher
Mohamed Daher

Reputation: 709

MongoDB Unique Index on array element across documents (not across nested document)

I have a Schema as follows:

Schema = mongoose.Schema    
User= new Schema
    { name: String,
     phones: [
    {
      confirmed: {
        type: Boolean,
        default: false
      },
      number: {
        type: String,
        unique: true
      }
  ]}  

This was supposed not to allow creation of 2 documents with same phone number. I understand that the index cant be unique across array elements so i am fine of having 1 document with 2 same numbers in the nested document but i dont want 2 documents to have same number. The index is not being created. I checked for existing duplicate documents that might be not allowing the index to be created but there is not. I tried creating the index in atlas with

{ "phones.number": 1 }, {unique:true}

it simply doesnt create it

Upvotes: 0

Views: 88

Answers (1)

J.F.
J.F.

Reputation: 15235

To do this you need to change a few things.

First of all, your schema has to be an index like this:

number: {
  type: String,
  index: true, // <-- This line
  unique: true
}

And, in your conections option add useCreateIndex: true. For example, I have:

const mongooseOpts = {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
    useCreateIndex: true //<-- This line
};

await mongoose.connect(uri, mongooseOpts);

Then, when you try to add a duplicate number phone an error will be thrown.

BulkWriteError: E11000 duplicate key error dup key: { : "1" }

With these two steps, if also didn't work, try removing the collection and creating again.

Upvotes: 1

Related Questions