使两个字段的组合在我的收藏中独一无二

Make combination of two fields unique in my collection

本文关键字:组合 我的 收藏 独一无二 字段 两个      更新时间:2023-09-26

我使用以下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的文档,但它们都不应该具有相同的onetwo组合。

Mongoose能做到这一点吗?

您可以对复合索引强制执行唯一约束,并且您可以在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 );