Answer the question
In order to leave comments, you need to log in
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 }"
}
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
};
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);
})
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question