gpt4 book ai didi

node.js - Mongoose 在子文档属性上强制执行唯一属性

转载 作者:可可西里 更新时间:2023-11-01 09:26:21 26 4
gpt4 key购买 nike

我不知道为什么在这些情况下未验证唯一属性

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 documentation解释:

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.

由于您处理的是嵌入式文档,因此您无法对同一父文档的嵌入式文档数组中的属性强制执行唯一性。

但是,当您随后尝试插入一个新的 Customer 且用户的电子邮件地址也为 mg@google.com 时,您将收到错误消息(但仅在保存时,而不是在使用 .push() 时,因为唯一性是由 MongoDB 而非 Mongoose 强制执行的)。

关于node.js - Mongoose 在子文档属性上强制执行唯一属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34383928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com