javascript - MongoError:E11000 重复键错误集合:test.users 索引:email1_1 重复键:{ email1:null }
问题描述
每当我尝试注册用户时,它都会给我这个错误
我检查了数据库集合并且不存在这样的重复条目,让我知道我做错了什么?
仅供参考 - req.body.email 和 req.body.password 正在获取值。
我也检查了这篇文章,但没有帮助堆栈链接
如果我完全删除,那么它会插入文档,否则即使我在 local.email 中有一个条目,它也会抛出错误“重复”错误
Server started on port 5000
MongoDB Connected
MongoError: E11000 duplicate key error collection: test.users index: email1_1 dup key: { email1: null }
{ driver: true,
name: 'MongoError',
index: 0,
code: 11000,
keyPattern: { email1: 1 },
keyValue: { email1: null },
errmsg: 'E11000 duplicate key error collection: test.users index: email1_1 dup key: { email1: null }',
[Symbol(mongoErrorContextSymbol)]: {}
}
以下是我在 user.js 模型架构中的用户架构
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {type: String, unique: true, required: true
},
resetPasswordToken: String,
resetPasswordExpires: Date,
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
路线
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
const async = require("async");
const nodemailer = require("nodemailer");
const crypto = require("crypto");
// Load User model
const User = require('../models/User');
const { forwardAuthenticated } = require('../config/auth');
// Login Page
router.get('/login', forwardAuthenticated, (req, res) => res.render('login'));
// Register Page
router.get('/register', forwardAuthenticated, (req, res) => res.render('register'));
// Register
router.post('/register', (req, res) => {
const { name, email, password, password2 } = req.body;
let errors = [];
if (!name || !email || !password || !password2) {
errors.push({ msg: 'Please enter all fields' });
}
if (password != password2) {
errors.push({ msg: 'Passwords do not match' });
}
if (password.length < 6) {
errors.push({ msg: 'Password must be at least 6 characters' });
}
if (errors.length > 0) {
res.render('register', {
errors,
name,
email,
password,
password2
});
} else {
User.findOne({ email: email }).then(user => {
if (user) {
errors.push({ msg: 'Email already exists' });
res.render('register', {
errors,
name,
email,
password,
password2
});
} else {
const newUser = new User({
name,
email,
password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => {
req.flash(
'success_msg',
'You are now registered and can log in'
);
res.redirect('/users/login');
})
.catch(err => console.log(err));
});
});
}
});
}
});
// Login
router.post('/login', (req, res, next) => {
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/users/login',
failureFlash: true
})(req, res, next);
});
// Logout
router.get('/logout', (req, res) => {
req.logout();
req.flash('success_msg', 'You are logged out');
res.redirect('/users/login');
});
module.exports = router;
解决方案
问题是,正如我从错误消息中看到的那样,您似乎在数据库中有一个没有电子邮件的实体(基本上email = null
)。并且因为您已将 email 字段指定为unique,所以 mongoDB 认为没有 email 是唯一的,因此集合中只能有一个没有 email 字段的实体。而且您正在尝试添加另一个没有电子邮件的实体,最终出现错误,因为该实体在数据库中也没有电子邮件作为记录。
您只需要在将电子邮件发送到数据库之前验证是否存在电子邮件,或实施适合您业务逻辑的其他解决方案。
希望能帮助到你 :)
推荐阅读
- browser - 无法识别有关 snapinsPage 的本地存储项目
- javascript - 在 Angular 中将一个数组类转换为另一个数组类
- applescript - 升级到 Catalina 后无法在 AppleScript 中获取智能相册
- c++ - 花括号内的结构声明
- angular - JUnit 测试用例出错。“没有找到测试运行器'JUnit'的测试
- r - 从其他多列的值有条件地替换多列的值
- google-apps-script - “需要授权”和@OnlyCurrentDoc
- python - Pandas Dataframe 错误'StringArray 需要一系列字符串或 pandas.NA'
- python - Tkinter 绘制 jpeg 或 png
- python - 如何将两个熊猫数据框放在一起,一个数据框缺少日期