Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 尽管在Mongoose中电子邮件设置为唯一,但能够使用相同的电子邮件创建多个用户_Javascript_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Javascript 尽管在Mongoose中电子邮件设置为唯一,但能够使用相同的电子邮件创建多个用户

Javascript 尽管在Mongoose中电子邮件设置为唯一,但能够使用相同的电子邮件创建多个用户,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我正在使用Express、MongoDB和Mongoose编写一个API。我可以用同一封电子邮件创建多个用户。但是,我不能创建具有相同电子邮件地址的其他用户。我的用户模式中有电子邮件unique:true,但这并没有按预期工作 以下是我的用户模式: var UserSchema = new Schema({ fullName: { type: String, required: [true, 'Full name is required.'] }, emailAddress: { typ

我正在使用Express、MongoDB和Mongoose编写一个API。我可以用同一封电子邮件创建多个用户。但是,我不能创建具有相同电子邮件地址的其他用户。我的用户模式中有电子邮件
unique:true
,但这并没有按预期工作

以下是我的用户模式:

var UserSchema = new Schema({
fullName: { type: String, required: [true, 'Full name is required.'] },
emailAddress: {
    type: String, required: true, unique: true,
    validate: {
        validator: function (value) {
            // check for correct email format
            return /^[a-zA-Z0-9.!#$%&’*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(value)
        },
        message: `Please enter a valid email address!`
    }
},
password: { type: String, required: true }
});
我的用户身份验证方法:

UserSchema.statics.authenticate = function (email, password, callback) {
User.findOne({ emailAddress: email })
    .exec(function (err, user) {
        if (err) {
            return callback(err);
        } else if (!user) {
            var error = new Error('User not found');
            error.status = 401;
            return callback(error);
        }
        bcrypt.compare(password, user.password, function (error, user) {
            if (user) {
                return callback(null, user);
            } else {
                return callback();
            }
        });
    });
}
用于散列密码的预保存挂钩:

UserSchema.pre('save', function (next) {
var user = this;
bcrypt.hash(user.password, 10, function (err, hash) {
    if (err) {
        return next(err);
    }
    user.password = hash;
    next();
});
});
最后,我的用户创建路线:

router.post('/', function (req, res, next) {
if (req.body.fullName &&
    req.body.emailAddress &&
    req.body.password &&
    req.body.confirmPassword) {

    if (req.body.password != req.body.confirmPassword) {
        var err = new Error('Passwords do not match!');
        err.status = 400;
        return next(err);
    }

    // object with form input
    var userData = {
        fullName: req.body.fullName,
        emailAddress: req.body.emailAddress,
        password: req.body.password
    };

    // schema's 'create' method to insert document into Mongo
    User.create(userData, function (error, user) {
        if (error) {
            var err = new Error('Please enter a valid email.');
            err.status = 400;
            return next(err);
        } else {
            // set location header to '/', return no content
            res.status(201);
            res.location('/');
            req.session.userId = user._id;
            return res.json(user);
        }
    });

} else {
    var err = new Error('All fields required.');
    err.status = 400;
    return next(err);
}
});

如果字段值中已存储重复项,则MongoDB不会为字段创建唯一索引

在您的情况下,emailAddress必须在数据库中存储重复项。 您可以通过运行代码来检查它

猫鼬 .model(#modelName) .collection.createIndex({“inviteCode”:1})

运行此代码后,您应该能够在控制台中看到错误消息

或者,如果您有重复的代码,您可以运行下面的代码进行检查。如果有副本,以下文件将获取:

猫鼬 .model(#modelName).aggregate([{ “$group”:{ “_id”:“$loginStatus”, 计数:{$sum:1}, id:{$push:“$\u id”} } },{$match:{ 计数:{$gt:1} }}])


如果您的电子邮件地址已经重复,则无法在其上创建唯一:true。您必须运行第二个查询并找出重复的电子邮件地址。您可以在
ids
数组中找到包含重复电子邮件的文档。

您的用户文档是否有一个
\u id
字段,并分配了
ObjectId
?@wscourge是的,下面是返回的内容,并自动生成
\u id
(不确定您所说的
ObjectId
是什么意思,但我相信
\u id
字段的值就是您要查找的内容。
{“\u v”:0,“全名”:“John Smith”,“emailAddress”:”john@smith.com“,”密码“$2a$10$P.VQVungzx9wMyKrI7nOu.1Sh5ikfB1SYUpzi/hFqqu.Ae4wM4c2。”,”id“:”59e657e08d643599fe1de35a”}
如果您在测试环境中,您可以尝试关闭应用程序,在mongoose连接语句之后插入
mongoose.set('debug',true)
(用于详细调试),关闭mongod,然后重新启动mongod和您的应用程序。您可能会遇到此问题,因为在将unique设置为true后尚未创建索引。有关详细信息,请参阅。重新启动应用程序应创建索引,然后unique可能会工作。