【问题标题】:Make combination of two fields unique in my collection [duplicate]组合我的收藏中唯一的两个字段[重复]
【发布时间】:2016-04-16 23:35:50
【问题描述】:

我正在使用以下 Mongoose 模型:

var Test = db.model('Test', db.Schema({
        one: { type: String, required: true },
        two: { type: String, required: true }
    },
    { strict: false })
);

它有两个必填字段,onetwo,以及strict:false,因为可能还有其他字段名称未定。

我希望onetwo组合 是独一无二的。这意味着可能有多个文档具有相同的one 或相同的two,但它们都不应该具有相同的one two 组合。

这可以用 Mongoose 实现吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您可以强制执行 unique constraint on compound indexes,您可以在 Mongoose 中使用架构的 index() 方法执行此操作,该方法在架构级别定义索引:

    var testSchema = db.Schema({
        "one": { "type": String, "required": true },
        "two": { "type": String, "required": true }
    }, { "strict": false });
    
    testSchema.index({ "one": 1, "two": 1}, { "unique": true });
    var Test = db.model("Test", testSchema );
    

    【讨论】:

    • 如果“two”是另一个模式的引用,有什么办法可以做同样的事情吗?谢谢
    • 1"one": 1 中提供的值是多少?
    • @AkashTomar 1 表示升序
    • @chridam 我已经按照你说的做了,但没有任何效果。这是我的问题。如何使复合索引真正唯一? stackoverflow.com/questions/63324015/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2019-01-04
    相关资源
    最近更新 更多