mongoose在子文档属性上强制执行唯一的属性
我不明白为什么独特的属性没有在这种情况下validation
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], });
当我推入新的用户到客户用户数组我可以添加相同的用户使用相同的电子邮件属性,而不会引起我期望的重复错误。
如果没有提供属性值而是唯一的,则所需的属性会出现错误
这是预期的行为?
例如:
var customer = new Customer(); customer.name = 'customer_name'; customer.save(...); for(var i = 0; i < 10; i++){ var user = new User(); user.email = 'mg@google.com'; customer.users.push(user); customer.save(...); }
MongoDB文档解释:
唯一的约束适用于集合中的单独文档。 也就是说,唯一索引可以防止单独的文档具有相同的索引键值,但索引不会阻止索引数组中具有多个元素或embedded文档的文档具有相同的值。
由于您正在处理embedded式文档,因此无法在同一父文档的embedded式文档的数组内的属性上实施唯一性。
但是,当您随后尝试插入一个新的Customer
并将其用户也以mg@google.com
作为电子邮件地址时,您将收到一个错误消息(但仅在保存期间,而不是在使用.push()
,因为唯一性由MongoDB强制执行,而不是Mongoose)。