在 Mongoose Schema 中使用多个值的唯一文档 [英] Unique documents using multiple values in Mongoose Schema

查看:37
本文介绍了在 Mongoose Schema 中使用多个值的唯一文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特殊情况,我们的集合需要根据电子邮件地址和抽奖 ID 的组合来确保每个文档都是唯一的.我已经看遍了,但我找不到如何完成这种类型的验证.

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.

架构定义:

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: []
   }
});

推荐答案

您可以使用包含两个字段的唯一索引来强制执行此操作:

You can enforce that using a unique index that includes both fields:

submissionSchema.index({ email: 1, sweepstakes_id: 1 }, { unique: true });

这篇关于在 Mongoose Schema 中使用多个值的唯一文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆