使两个字段的组合在我的收藏中独一无二 [英] Make combination of two fields unique in my collection
问题描述
我正在使用以下猫鼬模型:
I'm using the following Mongoose model:
var Test = db.model('Test', db.Schema({
one: { type: String, required: true },
two: { type: String, required: true }
},
{ strict: false })
);
它有两个必填字段,一个
和两个
,以及 strict:false
,因为可能还有其他字段名称不确定.
It has two required fields,one
and two
, and strict:false
because there can be other fields with undetermined names.
我希望 one
和 two
的组合是唯一的.这意味着可能有多个文档具有相同的 one
或相同的 two
,但是它们都不应该具有相同的 one
,并且 两个
组合.
I would like the combination of one
and two
to be unique. That means there could be multiple documents with the same one
or the same two
, but none of them should have the same one
and two
combination.
猫鼬可以做到吗?
推荐答案
您可以强制执行 index()
方法,该方法在模式级别定义索引:>
You can enforce a unique constraint on compound indexes, and you can do this in Mongoose using the index()
method of the schema, which defines indexes at the schema level:
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 );
这篇关于使两个字段的组合在我的收藏中独一无二的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!