在我的收藏中组合两个独特的字段

时间:2016-01-12 11:16:56

标签: javascript node.js mongodb mongoose

我正在使用以下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实现吗?

1 个答案:

答案 0 :(得分:11)

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

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 );