单个mongodb指数

时间:2017-09-12 20:29:58

标签: node.js mongodb mongoose

我在mongodb中遇到过独特的问题。我有一系列对象,其中有一封电子邮件,这封电子邮件需要是唯一的,但我有机会拥有0或无限的员工。

他怎么能让这种空虚独特呢?

我的员工是:

 employees: [{
    first_name: {
        type: String,
        lowercase: true
    },
    second_name: {
        type: String,
        lowercase: true
    },
    office: {
        type: String
    },
    access: {
        name: {
            type: String,
            required: true
        },
        value: {
            type: Number,
            required: true
        }
    },
    status: {
        type: Boolean,
        required: true
    },
    email: {
        type: String, trim: true, index: {
            partialFilterExpression: {email: {$type: 'string'}}
        },
        unique: true,
        required: true
    },
    password: {
        required: true,
        type: String
    }
}]

这样他就接受了两封电子邮件。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

您传递的Schema对象可能无法正常运行,因为您正在嵌套' unique'属性为' index'属性,尝试这样的事情(它按预期工作):

employees: [{
    first_name: {
        type: String,
        lowercase: true
    },
    second_name: {
        type: String,
        lowercase: true
    },
    office: {
        type: String
    },
    access: {
        name: {
            type: String,
            required: true
        },
        value: {
            type: Number,
            required: true
        }
    },
    status: {
        type: Boolean,
        required: true
    },
    email: {
        type: String, trim: true, index: {
            partialFilterExpression: {email: {$type: 'string'}}
        },
        unique: true,
        required: true
    },
    password: {
        required: true,
        type: String
    }
}]

注意:数组字段上的唯一索引强制相同的值不能出现在集合中多个文档的数组中,但不会阻止相同的值在单个文档中出现多次& #39; s数组。因此,您需要确保在向阵列添加元素时的唯一性。即你必须通过你的app逻辑处理。