MongoDB错误:E11000重复键错误,集合为test.users,索引为email1_1,重复键值为{ email1: null }。

4
每次我尝试注册用户时都会出现这个错误。
我检查了数据库集合,没有重复的条目,告诉我我做错了什么?
FYI - req.body.email和req.body.password正在获取值。
我也查看了这篇文章,但没有帮助STACK LINK。
如果完全删除它,则会插入文档,否则会抛出“重复”错误,即使我在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模型中的用户模式Schema:


    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;


尝试停止您的MongoDB服务,然后再次启动。 - theankitkotnala
@theankitkotnala 我该怎么做? - CodaBae
1个回答

11
从错误消息中看,似乎你的数据库中有一个实体没有电子邮件地址(基本上是email = null)。因为你把email字段指定为唯一的,mongoDB认为没有电子邮件地址是独一无二的,所以集合中只能有一个没有电子邮件地址的实体。你现在试图添加另一个没有电子邮件地址的实体,但由于在数据库记录中这个实体也没有电子邮件地址,所以最终出现了错误。
你只需要在将电子邮件地址发送到数据库之前验证其是否存在,或者实施其他符合你业务逻辑的解决方案。
希望这能帮到你 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接