If you enable Mongoose debug logging with the equivalent of coffeescript mongoose.set('debug', true); , you will see what happens:
DEBUG: Mongoose: employees.ensureIndex({ email: 1 }) { safe: true, background: true, unique: true } DEBUG: Mongoose: departments.ensureIndex({ name: 1 }) { safe: true, background: true, unique: true } DEBUG: Mongoose: departments.ensureIndex({ 'employees.email': 1 }) { safe: true, background: true, unique: true }
By embedding the full EmployeeSchema in the DepartmentSchema employees array (and not just the ObjectId link), you create unique indexes for both employees.email and department.employees.email .
Therefore, when you create a new department without any employees, you "use" the undefined mailbox in the department.employees.email index as unique. Therefore, when you try to do this a second time, this unique value is already accepted, and you will get a Duplicate key error .
The best solution for this is probably to change DepartmentSchema.employees into an array of ObjectId references for employees instead of full objects. Then the index remains in the employees collection, where it belongs, and you do not duplicate the data and do not create opportunities for inconsistencies.
Johnnyhk
source share