如何指定字段是对象数组,数组对象具有唯一但在 Mongoose 中可选的属性之一?
How to specify field which is array of objects, objects of array has one of attribute as unique but optional in Mongoose?
这是我的员工个人信息架构
const mongoose = require('mongoose');
const PersonalInformationSchema = mongoose.Schema({
name: {
type: String,
required: true
},
emails: [{
email: {
type: String,
trim: true,
unique: true
},
isPrimary: {
type: Boolean
}
}]
}, {
timestamps: true
});
module.exports = mongoose.model('PersonalInformation', PersonalInformationSchema);
在我的例子中,我有数组 emails
,这对员工来说是可选的,但应该是唯一的。当我插入一条没有电子邮件的记录时,文档保存成功(使用空数组 emails: []
)但在下一次尝试时它说
"err": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: EmployeePersonalInformation.personalinformations index: emails.email_1 dup key: { : null }"
}
您可以将 sparse: true
添加到您的架构中,试试:
const PersonalInformationSchema = mongoose.Schema({
name: {
type: String,
required: true
},
emails: [{
email: {
type: String,
trim: true,
unique: true,
sparse: true
},
isPrimary: {
type: Boolean
}
}]
}, {
timestamps: true
});
The sparse property of an index ensures that the index only contain entries for documents that have the indexed field. The index skips documents that do not have the indexed field.
因此,当跳过空文档时,您不会从 unique
约束中得到错误。
这是我的员工个人信息架构
const mongoose = require('mongoose');
const PersonalInformationSchema = mongoose.Schema({
name: {
type: String,
required: true
},
emails: [{
email: {
type: String,
trim: true,
unique: true
},
isPrimary: {
type: Boolean
}
}]
}, {
timestamps: true
});
module.exports = mongoose.model('PersonalInformation', PersonalInformationSchema);
在我的例子中,我有数组 emails
,这对员工来说是可选的,但应该是唯一的。当我插入一条没有电子邮件的记录时,文档保存成功(使用空数组 emails: []
)但在下一次尝试时它说
"err": {
"driver": true,
"name": "MongoError",
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: EmployeePersonalInformation.personalinformations index: emails.email_1 dup key: { : null }"
}
您可以将 sparse: true
添加到您的架构中,试试:
const PersonalInformationSchema = mongoose.Schema({
name: {
type: String,
required: true
},
emails: [{
email: {
type: String,
trim: true,
unique: true,
sparse: true
},
isPrimary: {
type: Boolean
}
}]
}, {
timestamps: true
});
The sparse property of an index ensures that the index only contain entries for documents that have the indexed field. The index skips documents that do not have the indexed field.
因此,当跳过空文档时,您不会从 unique
约束中得到错误。