I have a special case where our collection needs to make sure each document is unique based on a combination of the email address, and the sweepstakes_id. I've looked all over, but I can't find how to accomplish this type of validation.
我有一个特殊情况,我们的集合需要根据电子邮件地址和sweepstakes_id的组合确保每个文档都是唯一的。我看了一遍,但我找不到如何完成这种类型的验证。
Schema definition:
架构定义:
var submissionSchema = new Schema({
client_id: {
type: Schema.Types.ObjectId,
ref: 'Client',
index: true
},
sweepstakes_id: {
type: Schema.Types.ObjectId,
ref: 'Sweepstakes',
index: true
},
email: {
type: String,
index: true
},
data: {
type: Schema.Types.Mixed,
default: []
}
});
1 个解决方案
#1
44
You can enforce that using a unique index that includes both fields:
您可以使用包含两个字段的唯一索引来强制执行该操作:
submissionSchema.index({ email: 1, sweepstakes_id: 1 }, { unique: true });
#1
44
You can enforce that using a unique index that includes both fields:
您可以使用包含两个字段的唯一索引来强制执行该操作:
submissionSchema.index({ email: 1, sweepstakes_id: 1 }, { unique: true });