【问题标题】:Unique documents using multiple values in Mongoose Schema在 Mongoose Schema 中使用多个值的唯一文档
【发布时间】:2012-12-26 08:24:33
【问题描述】:

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

架构定义:

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以强制使用包含两个字段的唯一索引:

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

    【讨论】:

    • 1 的作用是什么?
    • 我在这里找到了答案:stackoverflow.com/questions/12573753/…
    • 我听说使用索引不利于生产。有人知道一种适用于生产的方法吗?
    • 我在mongoosejs.com/docs/guide.html 找到了它,但也许我误解了,“当您的应用程序启动时,Mongoose 会自动为您架构中的每个定义的索引调用 ensureIndex。Mongoose 将依次为每个索引调用 ensureIndex,并且当所有 ensureIndex 调用成功或发生错误时,在模型上发出一个“索引”事件。虽然对开发很有利,但建议在生产中禁用此行为,因为创建索引会导致显着的性能影响。禁用该行为通过将架构的 autoIndex 选项设置为 false..."
    • @user1828780 这只是需要注意的部署问题。见here
    猜你喜欢
    • 2021-04-09
    • 2020-03-23
    • 2021-10-21
    • 2021-03-27
    • 2012-08-27
    • 2021-11-15
    • 2018-12-13
    • 2021-07-31
    相关资源
    最近更新 更多