Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(...);
}
like image 962
Gavello Avatar asked Dec 20 '15 17:12

Gavello


People also ask

What does unique true do in mongoose?

Mongoose doesn't handle unique on its own: { name: { type: String, unique: true } } is just a shorthand for creating a MongoDB unique index on name . For example, if MongoDB doesn't already have a unique index on name , the below code will not error despite the fact that unique is true.

What is Mongoose unique validator?

mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.

Can I use $in in mongoose?

For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.

How do I create a unique field in MongoDB schema?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .


1 Answers

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).

like image 76
robertklep Avatar answered Oct 05 '22 22:10

robertklep