我有这样的架构:
class Schemas
constructor: ->
@mongoose = require 'mongoose'
@schema = @mongoose.Schema
@EmployeeSchema = new @schema
'firstname': { type: String, required: true },
'lastname': { type: String, required: true },
'email': { type: String, required: true, index: { unique: true }, validate: /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/ },
'departmentId': { type: @schema.ObjectId, required: true }
'enddate': String,
'active': { type: Boolean, default: true }
@EmployeeSchemaModel = @mongoose.model 'employees', @EmployeeSchema
@DepartmentSchema = new @schema
'name': { type: String, required: true, index: { unique: true } }
'employees' : [ @EmployeeSchema ]
@DepartmentSchemaModel = @mongoose.model 'departments', @DepartmentSchema
Run Code Online (Sandbox Code Playgroud)
这样我就employees住在一个employee文件里面department
我有几个department文档,其中有许多employee文档存储在employees数组中.
然后我添加了一个新的,department但它包含没有employees.如果我再尝试添加另一个department没有employees,猫鼬产生Duplicate key error了employee.email这是一个必填字段场.该employee.email领域是必需的和独特的,它需要.
无论如何围绕这个?
如果您使用等效的coffeescript启用Mongoose调试日志记录,mongoose.set('debug', true);您可以看到发生了什么:
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 }
Run Code Online (Sandbox Code Playgroud)
通过嵌入全EmployeeSchema中employees的数组DepartmentSchema(而不只是一个ObjectId参考吧),那么您最终创建两个唯一索引employees.email和department.employees.email.
因此,当您创建一个department没有任何员工的新人时,您将"消耗" department.employees.email索引中未定义的电子邮件案例,这是唯一性.因此,当你第二次尝试这样做时,已经采用了这个独特的价值而且你得到了Duplicate key error.
对此最好的解决方法可能是更改DepartmentSchema.employees为ObjectId对员工的引用数组而不是完整对象.然后索引保留在employees它所属的集合中,并且您不会复制数据并创建不一致的机会.
| 归档时间: |
|
| 查看次数: |
8093 次 |
| 最近记录: |