【问题标题】:Mongoose Schema - Requiring one to be unique but not bothMongoose Schema - 要求一个是唯一的,但不是两者都是
【发布时间】:2013-05-22 01:32:55
【问题描述】:

我想存储一个电子邮件字符串和密码,其中只有 1 需要是唯一的。因此,某人可以使用具有 2 个不同密码(或 100 个)的相同电子邮件地址并拥有 100 个帐户,但所有密码必须不同,但是只要他们的电子邮件地址不是一样。

我似乎在任何 mongoose 架构文档中都找不到此类事情的任何示例。

使用我的 adreas 建议:

var userSchema = new Schema({
    email: {
        type: String,
        required: true,
        index: true
    },
    password: {
        type: String,
        required: true,
        index: true
    }
});
//either email or password must be unique if the other is not
userSchema.index({
    "email": 1,
    "password": 1
}, {
    unique: true
});

module.exports = mongoose.model('User', userSchema);

它仍然让我使用相同的电子邮件和相同的密码。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    Compound index 应该是你需要的。

    User.index({ email: 1, hashedPassword: 1 }, { unique: true });
    

    但是,像这样实施它可能会带来安全风险,因为您必须在两个帐户上使用相同的盐。只是不要存储纯文本。

    【讨论】:

    • 这满足了我的需要,但之后我需要删除数据库中所有不同意新规则的条目。然后它开始正常工作。
    猜你喜欢
    • 1970-01-01
    • 2011-03-14
    • 2016-08-27
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2011-10-29
    • 2015-12-21
    • 2018-02-21
    相关资源
    最近更新 更多