MongoError: E11000 duplicate key error collection: test.users index: email1_1 dup key: { email1: null }
MongoError: E11000 duplicate key error collection: test.users index: email1_1 dup key: { email1: null }
每次我尝试注册用户时都会出现此错误
我检查了数据库集合,不存在这样的重复条目,让我知道我做错了什么?
仅供参考 - req.body.email 和 req.body.password 正在获取值。
我也检查了这个 post 但没有帮助 STACK LINK
如果我完全删除然后它插入文档,否则它会抛出错误 "Duplicate" 错误,即使我在 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
)。并且因为您已将电子邮件字段指定为 unique,mongoDB 认为没有电子邮件是唯一的,因此集合中只能有一个实体没有电子邮件字段。你试图添加另一个没有电子邮件的实体,最终,你遇到了一个错误,因为这个实体在数据库中也没有电子邮件作为记录。
您只需要在将电子邮件发送到数据库之前验证是否存在电子邮件,或者实施适合您的业务逻辑的其他解决方案。
希望对您有所帮助:)
每次我尝试注册用户时都会出现此错误
我检查了数据库集合,不存在这样的重复条目,让我知道我做错了什么?
仅供参考 - req.body.email 和 req.body.password 正在获取值。
我也检查了这个 post 但没有帮助 STACK LINK
如果我完全删除然后它插入文档,否则它会抛出错误 "Duplicate" 错误,即使我在 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
)。并且因为您已将电子邮件字段指定为 unique,mongoDB 认为没有电子邮件是唯一的,因此集合中只能有一个实体没有电子邮件字段。你试图添加另一个没有电子邮件的实体,最终,你遇到了一个错误,因为这个实体在数据库中也没有电子邮件作为记录。
您只需要在将电子邮件发送到数据库之前验证是否存在电子邮件,或者实施适合您的业务逻辑的其他解决方案。
希望对您有所帮助:)