使两个字段的组合在我的收藏中独一无二 [英] Make combination of two fields unique in my collection

查看:48
本文介绍了使两个字段的组合在我的收藏中独一无二的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下猫鼬模型:

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,oneand 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.

猫鼬可以做到吗?

推荐答案

您可以强制执行

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆