N
N
Nikita Shchypylov2018-05-23 00:30:47
MongoDB
Nikita Shchypylov, 2018-05-23 00:30:47

When I try to create a user, I get E11000 duplicate key error collection?

Good night, I can't catch the bug. I create a user, but I get an error:

{
    "name": "MongoError",
    "message": "E11000 duplicate key error collection: Udemy.users index: UserSchema.email_1 dup key: { : null }",
    "driver": true,
    "index": 0,
    "code": 11000,
    "errmsg": "E11000 duplicate key error collection: Udemy.users index: UserSchema.email_1 dup key: { : null }"
}

Code : User.js
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
 
 
let UserSchema = new mongoose.Schema({
 email: {
  type: String,
  required: true,
  trim: true,
  minlength: 1,
  unique: true,
  validate: {
   validator: validator.isEmail,
   message: '{VALUE} is not a valid email'
  }
 },
 password: {
  type: String,
  require: true,
  minlength: 6
 },
 tokens: [{
  access: {
   type: String,
   required: true
  },
  token: {
   type: String,
   required: true
  }
 }]
});
 
 
UserSchema.methods.toJSON = function () {
 let user = this;
 let userObject = user.toObject();
 
 return _.pick(userObject, ['_id', 'email']);
};
 
 
UserSchema.methods.generateAuthToken = function () {
 let user = this;
 let access = 'auth';
 let token = jwt.sign({_id: user._id.toHexString(), access}, 'abc123').toString();
 user.tokens = user.tokens.concat([{access, token}]);
 return user.save().then(() => {
  return token;
 });
};
 
let User = mongoose.model('User', UserSchema);
 
module.exports = {
 User
};

server.js :
app.post('/users', (req, res) => {
 let body = _.pick(req.body, ['email', 'password']);
 let user = new User(body);
 
 user.save().then(() => {
  return user.generateAuthToken();
 }).then((token) => {
  res.header('x-auth', token).send(user);
 }).catch((e) => {
  res.status(400).send(e);
 })
});

Full code here
Thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
levchak0910, 2018-05-23
@levchak0910

duplicate key error collection: UserSchema.email
You are trying to write to the database, a new user with a busy mail. Either you do not specify it, and the null value is set, which is also most likely already there

email: {
  unique: true,
  ...
 },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question