Gavello
Gavello

Reputation: 1491

mongoose enforce unique attribute on subdocument property

I can't tell why unique attribute is not validated in these case

var UserSchema = new mongoose.Schema({
  name: { type: String},
  email: { type: String, unique: true, required: true },
});

var CustomerSchema = new mongoose.Schema({
   name: { type: String, unique: true, required: true },
   users:[UserSchema],
});

When i push a new user into customer users array i can add the same user with the same email property without raising the duplicate error i would expect.

required attribute rise the an error if property vale is not provided but unique does not

Is this the expected behavior?

for example:

var customer = new Customer();
customer.name = 'customer_name';
customer.save(...);

for(var i = 0; i < 10; i++){
   var user = new User();
   user.email = '[email protected]';
   customer.users.push(user);
   customer.save(...);
}

Upvotes: 5

Views: 2338

Answers (1)

robertklep
robertklep

Reputation: 203554

The MongoDB documentation explains:

The unique constraint applies to separate documents in the collection. That is, the unique index prevents separate documents from having the same value for the indexed key, but the index does not prevent a document from having multiple elements or embedded documents in an indexed array from having the same value.

Since you're dealing with embedded documents, you can't enforce uniqueness on a property within the array of embedded documents of the same parent document.

However, when you subsequently try to insert a new Customer with a user that also has [email protected] as e-mail address, you will get an error (but only while saving, not when using .push(), because uniqueness is enforced by MongoDB, not Mongoose).

Upvotes: 5

Related Questions