Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoError: E11000 duplicate key error collection: test.users index: email1_1 dup key: { email1: null } [duplicate]

any time i try to register a user it gives me this error

I checked the db collection and no such duplicate entry exists, let me know what I am doing wrong ?

FYI - req.body.email and req.body.password are fetching values.

I also checked this post but no help STACK LINK

If I removed completely then it inserts the document, otherwise it throws error "Duplicate" error even I have an entry in the 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)]: {}
    }

Following is my user schema in user.js model 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;

Route


    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;

like image 329
CodaBae Avatar asked Jan 26 '23 09:01

CodaBae


1 Answers

The thing is that, as I see from the error message, it seems like you have one entity in the DB which has no email(basically email = null). And because you've specified email field as unique, mongoDB thinks that not having an email is unique, so there can only be one entity with no email field in the collection. And you're trying to add another entity with no email, and eventually, you have an error, because this entity also has no email as a record in the DB.

You just need to verify if email is present, before sending it to DB, or implement other solution that fits for your business logic.

Hope it helps :)

like image 147
Max Avatar answered Jan 31 '23 05:01

Max